I'm trying to do a home work assignment which requires data fro a txt file to be read in to variables. The file has this on each line "surname, initials, number, number". I have got the get line working partially using the following code.
ifstream inputFile("Students.txt");
string line;
string Surname;
string Initial;
int number1, number2;
while (getline(inputFile, line))
{
stringstream linestream(line);
getline(linestream, Surname, ',');
getline(linestream, Initial, ',');
getline(linestream, number1, ',');
getline(linestream, number2, ',');
cout << Surname << "---" << Initial << "-" << number1 << "-" << number2 << endl;
}
This throws a compile error, but if I declare number1 and number2 as strings it works fine. So my question is, do I have to getline as a string then convert to an int variable or is there a better way?
std::getline
takes as a first parameter an object ofstd::basic_istream
. It won't work for any other object.What I did was use the
csv_whitespace
class to add a comma as a delimeter. For example:Yes, the second parameter of getline function must be a string by definition and it will contain your extracted string. Simply declare number1 and number2 as string and then convert them to Integer with stoi() (C++11) or atoi() function :
Hope this helps