Can't make atoi take in a string (string vs. C-string?)

user2333388 picture user2333388 · May 2, 2013 · Viewed 24k times · Source

I have read a line from a file and I am trying to convert it to an int. For some reason atoi() (convert string to integer) won't accept a std::string as an argument (possibly some issue with strings vs c-strings vs char arrays?) - how do I get atoi() to work right so I can parse this text file? (going to be pulling lots of ints from it).

Code:

int main()
{
    string line;
    // string filename = "data.txt";
    // ifstream file(filename)
    ifstream file("data.txt");
    while (file.good())
    {
        getline(file, line);
        int columns = atoi(line);
    }
    file.close();
    cout << "Done" << endl;
}

The line causing problems is:

int columns = atoi(line);

which gives the error:

error: cannot convert 'std::string' to 'const char*' for argument '1' to 'int atop(const char*)'

How do i make atoi work properly?

EDIT: thanks all, it works! new code:

int main()
{
string line;
//string filename = "data.txt";
//ifstream file (filename)
ifstream file ("data.txt");
while ( getline (file,line) )
{
  cout << line << endl;
  int columns = atoi(line.c_str());
  cout << "columns: " << columns << endl;
  columns++;
  columns++;
  cout << "columns after adding: " << columns << endl;
}
file.close();
cout << "Done" << endl;
}

also wondering why string filename = "data.txt"; ifstream file (filename) fails, but

    ifstream file("data.txt");

works? ( I will eventually be reading filename form the command line so need to make it not a string literal)

Answer

john picture john · May 2, 2013

The c_str method exists for this purpose.

int columns = atoi(line.c_str());

BTW your code should read

while (getline (file,line))
{
    ...

Just because the file is 'good' does not mean the next getline will succeed, only that the last getline succeeded. Use getline directly in your while condition to tell if you did actually read a line.