c++ - 程序只输入一行到文本文件

标签 c++ file text input output

我的程序只从文本文件中输入一次数字。我还注意到给定数字的最后一行用于计算。如果我试图在 while 循环中这样做是不是很糟糕?如果可以,我还能怎么做?

人数是:

5
100 1 20
120 1 45
90 1 05
105 1 25
100 1 35

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    double d,a,b,c,g=0;
    ifstream file("Text.txt");
    if(file.is_open())
    {
        file >> d;
        cout << d << endl;
        while(file >> a >> b >> c)
        {
            cout << left << setw(3) << a << " " << b << " " << c << endl;
            g=a/(b*60+c);
            ofstream files("Result.txt");
            files << "Speed: " << g << " m/s" << endl;
        }
    }
    return 0;
}

最佳答案

循环中的这一行有问题

        ofstream files("Result.txt");

每次您从输入中读取时,它都会创建一个 文件。因此它将只包含最后一次输入的输出。

如果将该行移动到 while 之前,您将在同一个文件中获得所有输出。

关于c++ - 程序只输入一行到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33068418/

相关文章:

C++ 流对象线程安全吗?

file - 移动名称中有空格的文件

ios - 在 ios 上用 C 读取大文本文件

c++ - 不好了!我的文字闪烁?

c++ - 反向迭代器错误 : no match for 'operator!=' in 'rcit != std::vector<_Tp, _Alloc>::rend() with _Tp = int, _Alloc = std::allocator'

c++ - 如何从 Init 强制 gtest 将报告写入 xml

algorithm - 统一文件访问

file - 使用 Junit 比较两个 xml 文件

Excel 公式不起作用 - 无法识别数字

c# - 异常助手不工作