Andy
Andy

Reputation: 281

Read from a file then convert from to int?

I wrote this function that is supposed to read from a file containing ACII decimal numbers and convert these to integers stored in an int array. Here is that function:

void readf1()
{
    int myintArray[100];
    int i = 0;
    int result;
    string line = "";
    ifstream myfile;
    myfile.open("f1.txt");

    if(myfile.is_open()){
      //while not end of file
      while(!myfile.eof()){
        //get the line
        getline(myfile, line);

        /* PROBLEM HERE */
        result = atoi(line);

        myintArray[i] = result;
        //myintArray[i]
        cout<<"Read in the number: "<<myintArray[i]<<"\n\n";
        i++;
     }
  }
}

The problem is that atoi is not working. The error I get is cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'. I'm not sure why its not working as I looked at examples and I am using it exactly the same. Anyone know what I may be doing wrong?

Upvotes: 4

Views: 11646

Answers (3)

David G
David G

Reputation: 96790

atoi is a C function that accepts a C-string, not a C++ std::string. You need to obtain the raw char* from the string object to use as the argument. The method for this is .c_str():

atoi(line.c_str());

The C++ equivalent of atoi is std::stoi (C++11):

std::stoi(line);

Moreover, while (!file.eof()) is considered a bad practice. It's better to do the I/O operation inside the expression so the stream object is returned and valid file conditions are assessed thereafter:

while (std::getline(myfile, line))

Your code can be improved further, however. Here is how I would do it:

#include <vector>

void readf1()
{
    std::vector<int> myintArray;

    std::string line;
    std::ifstream myfile("f1.txt");

    for (int result; std::getline(myfile, line); result = std::stoi(line))
    {
        myintArray.push_back(result);

        std::cout << "Read in the number: " << result << "\n\n";
    }
}

Upvotes: 7

Patrik
Patrik

Reputation: 2691

You can use

result = atoi(line.c_str());

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

atoi() wants a char *, not a string:

result = atoi(line.c_str());

Upvotes: 1

Related Questions