【问题标题】:How to read in only numbers from a text file in C++如何从 C++ 中的文本文件中仅读取数字
【发布时间】:2018-02-12 21:13:41
【问题描述】:

我正在尝试从如下所示的文件中读取每个月的平均降雨量:

一月 3.2 二月 1.2 三月 2.2

8 月 2.3 日 9 月 2.4 日

我需要输入前 3 个数字并获得它们的平均值以及第 3 个月(3 月)的输出。我目前有这个代码:

#include <fstream>

#include <string>

using namespace std;

int main()    
{    
    ifstream inputFile;
    string name;
    double num = 0, many = 0, total = 0, value = 0;

    inputFile.open("Rainfall.txt");


    for (int count = 1; count <= 6; count++)
    {
        inputFile >> name;

        if (count == 1 || count == 3 || count == 5)
        {               
            continue;    
        }

        name += total;    
        cout << name << endl;     
    }

    for (int inches = 1; inches <= 6; inches++)
    {
        inputFile >> name;

        if (inches == 1 || inches == 3 || inches == 5)
        {
            continue;
        }

        cout << name << endl;
    }

    inputFile.close();          
    return 0;
}

输出看起来像:

3.2
1.2
2.2
2.3
2.4
2.4

现在我不能添加前 3 个数字,因为它们是字符串,我需要它们是双精度数。

【问题讨论】:

标签: c++ loops average


【解决方案1】:

如果name number的格式是一致的,可以粗略阅读:

std::string name;
double number = 0, total = 0;

while(inputFile >> name >> number)
{
    cout << name << ' ' << number << '\n';
    total += number;
}

【讨论】:

  • 正确的格式是一样的,但我只需要输出前3个数字的平均值来显示。出于某种原因,我运行了您的代码并且根本没有输出。不知道为什么
猜你喜欢
  • 2012-11-10
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
相关资源
最近更新 更多