Reputation: 149
So I have a file that has multiple columns of data like this:
1 2 3
4 5 6
7 8 9
etc...
And I'm traversing through this file with a while loop trying to store the data in a vector as I go along. But when I use a delimiter to deal with the spaces in between the data it only reads the first line and stops. The code for the while loop is as follows:
while(getline(infile,content, ' '))
{
double temp = atof(content.c_str();
cout << "value storing is: " << temp << endl;
data.push_back(temp);
}
Using the data above with this code I just get "1 2 3" as the output. So i'm not sure where I'm going wrong with this.
The column the numbers are in are also important when I crunch the data later. For example, every iteration of the while loop will add a counter and every time it goes to a new line will be another counter so with that i can figure out how many lines I have so when I need to compute something I can use i%(columnNumber) to grab that value.
Thanks for any light anyone can shed on my situation.
Upvotes: 0
Views: 151
Reputation: 437
It's because there are no spaces after a new line.
This is what the file looks like (to std::getline()
)
1 space 2 space 3 newline 4 space 5 space 6 newline 7 space 8 space 9
I can't reproduce "1 2 3" as output. When I run your code, I get
value storing is: 1
value storing is: 2
value storing is: 3
value storing is: 5
value storing is: 6
value storing is: 8
value storing is: 9
where my test file looks like this:
1 2 3
4 5 6
7 8 9
To fix the problem, try doing something like this:
int main()
{
std::ifstream in("test");
std::string content;
std::vector<int> data;
while (getline(in, content))
{
std::stringstream linestream(content);
int value;
// Read an integer at a time from the line
while(linestream >> value)
{
// Add the integers from a line to a 1D array (vector)
data.push_back(value);
std::cout << "value storing is: " << value << std::endl;
}
}
}
Upvotes: 2