views:

237

answers:

3

Hi

I need to read different values stored in a file one by one. So I was thinking I can use ifstream to open the file, but since the file is set up in such a way that a line might contain three numbers, and the other line one number or two numbers I'm not sure how to read each number one by one. I was thinking of using stringstream but I'm not sure if that would work.

The file is a format like this.

52500.00       64029.50      56000.00
65500.00       
53780.00       77300.00     
44000.50       80100.20      90000.00      41000.00    
60500.50       72000.00

I need to read each number and store it in a vector.

What is the best way to accomplish this? Reading one number at a time even though each line contains a different amount of numbers?

+6  A: 

Why not read them as numbers from the file?

double temp;
vector<double> vec;
ifstream myfile ("file.txt");

if (myfile.is_open()) {
  while ( myfile >> temp) {
    vec.push_back(temp);
  }
  myfile.close();
}
codaddict
hmm i was doing something close to this, but yeah it's better to just read them as numbers. thanks
+1  A: 

If you don't care about position of numbers I propose using istringstream after getline :

std::ifstream f("text.txt");
std::string line;
while (getline(f, line)) {
    std::istringstream iss(line);
    while(iss) {
        iss >> num1;
    }
}
Basilevs
A: 
vector<double> v;
ifstream input ("filename");
for (double n; input >> n;) {
  v.push_back(n);
}
Roger Pate