Reading from file and spliting string and converting strin to int

Hi

I was trying to create a program that gets a file name from console and then it reads the two numbers, converts those two numbers into long int. But as i separate the line and try to convert it into long int I cannot distinguish the two lines from each other.

// basic file operations
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main (int argc, char * argv[]) {
string line;
char * fileName = argv[1];
ifstream myfile (fileName);
if (myfile.is_open())
{
while ( myfile.good() )
{

getline(myfile, line,' ');
long a = atoi(line.c_str());//this the place where is the problem
long b = atoi(line.c_str());
cout << a << endl;
cout << b << endl;

}
myfile.close();
}
else cout << "No such file";
return 0;
}
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// basic file operations
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main (int argc, char * argv[])
{
  string line;
  // You should check if argc > 1 before attempting assignment here.
  char *fileName = argv[1];
  
  ifstream myfile (fileName);
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      //getline(myfile, line,' ');
      
      // Try myfile >> line;
      myfile >> line;
      // If you want multiple varaibles try an array or just more than one myfile >> line
      long a = atoi( line.c_str() );
      //long b = atoi(line.c_str());
      cout << a << endl;
      //cout << b << endl;

      }
    myfile.close();
  }
  else cout << "No such file\n";

  return 0;
}
A lot of thanks man
myfile >> line;

Worked just fine!
Can close this topic.
Topic archived. No new replies allowed.