我正在尝试编写一个程序来读取文件并计算诸如平均值和最大值之类的东西。当文件中只有数值时,该程序可以正常工作,但程序需要能够读入值,直到遇到任何非数值,并根据遇到字符之前读取的值计算平均值等。我不知道该怎么做。
我尝试了一个使用 isAlpha
的 if 语句,但如果文件中有非数值,则在我输入它正在查找的文件的名称后,程序就卡住了。
//Function to open object and file by the name that was entered
ifstream inFile;
inFile.open(fileName);
//checking for error, sends error message if unable to open
if(inFile.fail()){
cerr << "This file is unable to be opened.\n";
exit(1);
}
//Goes on to complete necessary functions if input is valid
else
{
//loop with the condition being a function that checks to the end of the file
//so the items are read in till the end of the file
while(!inFile.eof()){
//almost like cin, values are read in from the object inFile and stored in variable readIn;
inFile >> readIn;
//counter adds one for every line if value is existent
itemCount++;
//calculates product of values
product = product * readIn;
//stores largest value
if(max < readIn){
max = readIn;
}
//calculates sum of values
sum = sum + readIn;
//calculation of average
average = sum / itemCount;
}
最佳答案
我会读入一个字符串,然后将其转换为一个整数。将 cin 替换为您的流。
请注意 stoi 具有一些潜在的令人惊讶的特性,例如支持十六进制
https://en.cppreference.com/w/cpp/string/basic_string/stol
std::string s;
while (std::cin >> s) {
try {
int const val = std::stoi(s);
// process val
} catch(...) {
// probably should catch actual types but they are long and im on mobile
}
}
关于c++ - 如何从文本文件中读取数值直到遇到 char 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918759/