我对编程还比较陌生,目前正在学习 C++ 类(class)。到目前为止,我还没有遇到任何重大问题。我正在制作一个程序,其中 X 数量的评委可以得分 0.0 - 10.0(双倍),然后删除最高和最低的分数,然后计算并打印出平均值。
这部分已经完成,现在我想从一个文件中读取以下形状的文件:
示例.txt -
10.0
9.5
6.4
3.4
7.5
但我遇到了点 (.) 的问题以及如何绕过它以使数字变成 double 。有什么建议和(好的)解释可以让我理解吗?
TL;DR:从文件(例如“9.7”)读取一个 double 变量以放入数组。
由于您的文本文件是用空格分隔的,您可以利用默认情况下跳过空格的std::istream
对象(在本例中,std::fstream
):
#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
int main() {
std::ifstream ifile("example.txt", std::ios::in);
std::vector<double> scores;
//check to see that the file was opened correctly:
if (!ifile.is_open()) {
std::cerr << "There was a problem opening the input file!\n";
exit(1);//exit or do additional error checking
}
double num = 0.0;
//keep storing values from the text file so long as data exists:
while (ifile >> num) {
scores.push_back(num);
}
//verify that the scores were stored correctly:
for (int i = 0; i < scores.size(); ++i) {
std::cout << scores[i] << std::endl;
}
return 0;
}
注意:
强烈建议尽可能使用 vectors
代替动态数组,原因有很多,如下所述:
When to use vectors and when to use arrays in C++?