[英]How to read in only numbers from a text file in C++
我正在嘗試從看起來像這樣的文件中讀取每個月的平均降雨量:
一月3.2二月1.2三月2.2
八月2.3九月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
現在,我無法添加前三個數字,因為它們是字符串,並且我需要將它們加倍。
如果格式name number
是一致的,則可以簡單閱讀:
std::string name;
double number = 0, total = 0;
while(inputFile >> name >> number)
{
cout << name << ' ' << number << '\n';
total += number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.