Hello, im a bit new to c++ and learning in my own, but im stuck to a problem.
Im trying to do a practice converting string/c-string to int :

Sum of Digits in a String
Write a program that asks the user to enter a series of single digit numbers with nothing
separating them. Read the input as a C-string or a string object. The program
should display the sum of all the single-digit numbers in the string. For example, if the
user enters 2514, the program should display 12, which is the sum of 2, 5, 1, and 4.

so i make a simple program first like this :

#include <iostream>
#include <cstdlib>


using namespace std;

int main()
{
    const int size = 5;
    char array[size];
    int acc = 0;//for accumulator

    int number[5];

    for(int count = 0; count < size; count++)
    {
        cout<<"enter a number = ";
        cin>>array[count];
        number[count] = atoi(array[count]);
        acc += 0;

    }

    cout<<endl<<"the total number = "<<acc;


    return 0;
}

but theres problem in 'atoi' to convert the string, the compiler says = 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
anyone can help me?

Recommended Answers

All 2 Replies

first of all atoi(const char *str)..this means that atoi() takes a string as a parameter..what you are passing is a character only..so you need to convert it into a string which in c/c++ means a string ends with a '\0' character

char temp[2];
temp[1]='\0';
temp[0]=array[count];

this makes temp a string..now you can do

number[count]=atoi[temp];

ok thx i got it
so i made a simple program just for checking like this:

#include <iostream>
#include <cstdlib>


using namespace std;

int main()
{
    char asd[5] = "1234";
    char a[2];
    int num, acc = 0;
    for(int count = 0; count < 5; count++)
    {
        a[0] = asd[count];
        a[1] = '\0';
        num = atoi(a);
        acc += num;
    }
    cout<<acc;


    return 0;
}

and yep once again thx for the help :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.