C ++ - 从文件读取到双 [英] C++ - Read from file to double
问题描述
我现在相对来说是编程和学习C ++的课程。我到目前为止没有任何重大问题。我正在做一个程序,其中X数量判断可以得分0.0 - 10.0(双),然后删除最高和最低的一个,然后计算并打印出平均值。
I'm relatively new to programming and taking a course in C++ currently. I haven't had any major problems so far. I am making a program where an X amount judges can score 0.0 - 10.0 (double) and then the highest and lowest one is removed then an average is calculated and printed out.
这部分完成,现在我想从一个文件中读取形状:
example.txt -
10.0
9.5
6.4
3.4
7.5
This part is done, now I want to read from a file in the shape of: example.txt - 10.0 9.5 6.4 3.4 7.5
但我偶然发现了点(。)的问题,以及如何解决这个问题。任何建议和(好的)解释,以便我能理解它?
But I am stumbling onto problems with the dot (.) and how to get around it to get the number into a double. Any suggestions and (good) explanations so I can understand it?
TL; DR:
推荐答案
由于您的文本文件是空格分隔,可以通过使用默认跳过空格的 std :: istream
对象来使用它(在这种情况下, std :: fstream
):
Since your textfile is whitespace delimited, you can use that to your advantage by utilizing std::istream
objects who skip whitespace by default (in this case, 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;
}
注意:
强烈建议使用向量
代替动态数组,尽可能使用大量的原因:
It is highly recommended to use vectors
in lieu of dynamic arrays where possible for a myriad number of reasons as discussed here:
这篇关于C ++ - 从文件读取到双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!