0

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?

2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by Sendy Hipo
0

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];
0

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

Edited by Sendy Hipo

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.