atoi(textline[c]) iterating through getline?

550 views Asked by At

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 *);
         ^
2

There are 2 answers

2
GAVD On BEST ANSWER

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';
3
Sam Estep On

First things first, you have some typos in your code (txtline instead of textline).

You also have an index bounds error: if textline doesn't contain a space at all, i will fall off of the valid indices in textline, so you'll be accessing invalid data.

As for the error with atoi: the atoi function attempts to convert a C-style (null-terminated) string to an integer value. Your usage therefore is wrong: you're passing a char, but atoi requires a pointer to a char (in this case, a pointer a char that is interpreted as a C-style string). What exactly is the code you posted supposed to do?

If you need to use atoi, I would advise doing some more research into C-style strings. If you don't, I would advise using something more C++-ish, like stringstream, to get integers out of strings.