简体   繁体   中英

Read multiple strings from a file C++

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?

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();
}

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;
    }
}
vector<double> v;
ifstream input ("filename");
for (double n; input >> n;) {
  v.push_back(n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM