views:

51

answers:

1

I have this code that reads from marks.txt file.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main () {
  string name,result;
  int number1;
  ifstream myfile ("marks.txt");
  if (myfile.is_open())
  {
    while ( !myfile.eof() )
    {
      getline (myfile,name,'\t');
      getline (myfile,result,'\t');
      stringstream(result) >> number1;
      cout << number1;


    }

    myfile.close();

  }

  else cout << "Unable to open file";

  return 0;
}

with my marks.txt file consists of:

john 20

But when i ran the program. Number1 output is 36. How can i convert result string to int correctly??

+2  A: 

Note that you're passing \t (tab character) as the delimiter to getline. Are you sure you are using a tab in your input file? If you use a space or any other character, all the input will go into name and your result will be empty, which will leave number1 undefined. I suspect that's the reason you're getting 36 out of nowhere.

casablanca
Yeah. I kinda miss that. Thanks
diehell