Reputation: 1
I am trying to read a text file in my code using fstream. The text file has the following structure,
Main,Johnsons,4,4
Lake,Smiths,1,2
Orchid,Hendersons,3,8
I am trying to do the following.
Neighborhood n1;
ifstream houses;
houses.open("houses.txt");
string line;
string street;
string family;
int house;
int rooms;
int colptr = 1;
while (houses.good()) {
getline(houses, line, ',');
switch (colptr) {
case 1: {
col1 = line;
colptr++;
break;
}
case 2: {
col2 = line;
colptr++;
break;
}
case 3: {
col3 = stoi(line);
colptr++;
break;
}
case 4: {
col4 = stoi(line);
colptr = 1;
House h(col1, col2, col3, col4);
n1.addHouse(h);
break;
}
default: {
break;
}
}
}
House is a class that takes (string,string,int,int) to construct a House, and the method addHouse() of the Neighborhood class just adds the House to a list of houses.
The code throws an error because it is trying to convert a string to int. I caught that on the 4 iteration it will try to convert "4 Lake" to an integer - which it obviously can't do.
The code works if if format my text file with a ',' at the end like
Main,Johnsons,4,4,
Except this won't work for me because the text file I'm given is always like the one shown at the beginning.
Thank you in advance!
Upvotes: 0
Views: 1182
Reputation: 1168
You can call getline()
twice in a nested loop. First one reads input typically "line by line", the second one splits by the comma "," with assistance of a std::stringstream
object:
//...
while (houses.good()) {
getline(houses, line); //use default getline() - line by line
std::stringstream ss (line);
std::string word;
while (getline (ss, word, ',')) {
//... the rest of code
//...
Upvotes: 2
Reputation: 2554
You can get the line and add the ,
char at the end, and then get the words.
while (houses.good()) {
std::istringstream input;
getline(houses, line);
line += ',';
input.str(line);
for (std::string token; getline(input, token, ','); ) {
// process words
}
}
Upvotes: 0