从文件 C++ 读取多个字符串

发布于 2024-08-29 00:38:35 字数 432 浏览 4 评论 0 原文

我需要一一读取文件中存储的不同值。所以我想我可以使用 ifstream 打开文件,但由于文件的设置方式是一行可能包含三个数字,另一行可能包含一个数字或两个数字我'我不知道如何一一阅读每个数字。我正在考虑使用 stringstream 但我不确定这是否可行。

该文件是这样的格式。

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 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我一向站在原地 2024-09-05 00:38:35

为什么不从文件中将它们作为数字读取?

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

if (myfile.is_open()) {
  while ( myfile >> temp) {
    vec.push_back(temp);
  }
  myfile.close();
}

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();
}
执手闯天涯 2024-09-05 00:38:35

如果您不关心数字的位置,我建议在 istringstream href="http://www.cplusplus.com/reference/string/getline/" rel="nofollow noreferrer">getline :

std::ifstream f("text.txt");
std::string line;
while (getline(f, line)) {
    std::istringstream iss(line);
    while(iss) {
        iss >> num1;
    }
}

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;
    }
}
我三岁 2024-09-05 00:38:35
vector<double> v;
ifstream input ("filename");
for (double n; input >> n;) {
  v.push_back(n);
}
vector<double> v;
ifstream input ("filename");
for (double n; input >> n;) {
  v.push_back(n);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文