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?
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 :
string strNumber1;
string strNumber2;
getline(linestream, strNumber1, ',');
getline(linestream, strNumber2, ',');
int number1 = stoi(strNumber1);
int number2 = atoi(strNumber2.c_str());
Hope this helps
std::getline
takes as a first parameter an object of std::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:
class csv_whitespace
: public std::ctype<char>
{
public:
static const mask* make_table()
{
static std::vector<mask> v(classic_table(), classic_table() + table_size);
v[','] |= space;
v[' '] |= space;
return &v[0];
}
csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) { }
};
int main()
{
std::ifstream in("Students.txt");
std::string line;
std::string surname;
std::string initial;
int number1, number2;
while (std::getline(in, line))
{
std::stringstream linestream(line);
linestream.imbue(std::locale(linestream.getloc(), new csv_whitespace));
getline(linestream, surname, ',');
getline(linestream, initial, ',');
linestream >> number1 >> number2;
}
}