Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a file then convert from to int?

Tags:

c++

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?

like image 333
Andy Avatar asked Sep 01 '25 20:09

Andy


2 Answers

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";
    }
}
like image 54
David G Avatar answered Sep 09 '25 09:09

David G


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

result = atoi(line.c_str());
like image 44
Paul Roub Avatar answered Sep 09 '25 08:09

Paul Roub