Search code examples
c++getlineatoi

atoi(textline[c]) iterating through getline?


I'm new to C++, what can I do to perform something like:

getline(textfile, txtline);
int i = 0;
while (textline[i] != ' ') // Until space
{
    if (isdigit(txtline[i]) == true) 
        int n = atoi(txtline[i]);
        // Then code to use n
    i++;
}

atoi() is generating an error, but am I not just passing a char to it?

Here's the full error:

myqueens.cpp:32:11: error: no matching function for call to 'atoi'
                int n = atoi(txtline[i]);
                        ^~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/stdlib.h:132:6: note: candidate function not viable: no known conversion from 'value_type' (aka 'char') to 'const char *' for 1st argument; take the address of the argument with &
int      atoi(const char *);
         ^

Solution

  • The error is that atoi() expects a string (i.e. char*). So, you can get the message after debugging: cannot convert from 'const char' to 'char[]'.

    So, if you want to convert textline[i] to int, you can use

    int n = textline[i] - '0';