我目前对编程和学习 C++ 课程相对较新。到目前为止,我还没有遇到任何重大问题。我正在制作一个程序,其中 X 数量的评委可以得分 0.0 - 10.0(双倍),然后删除最高和最低的一个,然后计算并打印出平均值。
这部分完成了,现在我想从一个文件中读取:example.txt - 10.0 9.5 6.4 3.4 7.5
但是我偶然发现了点(。)的问题以及如何绕过它以使数字变成双倍。有什么建议和(好的)解释让我能理解吗?
TL;DR:从文件(例如“9.7”)读取双变量以放入数组中。
由于您的文本文件是空格分隔的,因此您可以通过使用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
动态数组来代替动态数组,原因有很多,如下所述:
尝试这个:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream fin("num.txt");
double d;
fin >> d;
std::cout << d << std::endl;
}
这样做是你想要的吗?