Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从文本文件中读取数值,直到遇到字符类型为止?_C++ - Fatal编程技术网

C++ 如何从文本文件中读取数值,直到遇到字符类型为止?

C++ 如何从文本文件中读取数值,直到遇到字符类型为止?,c++,C++,我正试图编写一个程序来读取一个文件并计算平均值和最大值等。当文件中只有数值时,程序工作正常,但程序需要能够读入值,直到遇到任何非数值,并根据遇到字符之前读取的值计算平均值等。我不知道该怎么办 我使用isAlpha尝试了一个if语句,但是在我输入了它正在查找的文件名(如果文件中有非数值)后,程序就卡住了 //Function to open object and file by the name that was entered ifstream inFile; inFile.open(fileN

我正试图编写一个程序来读取一个文件并计算平均值和最大值等。当文件中只有数值时,程序工作正常,但程序需要能够读入值,直到遇到任何非数值,并根据遇到字符之前读取的值计算平均值等。我不知道该怎么办

我使用
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;


    }
//按输入的名称打开对象和文件的函数
河流充填;
inFile.open(文件名);
//检查错误,如果无法打开,则发送错误消息
if(infle.fail()){
cerr>readIn;
//如果值存在,计数器将为每行添加一个值
itemCount++;
//计算值的乘积
产品=产品*读入;
//存储最大价值
如果(最大值<读数){
最大值=读数;
}
//计算值的总和
总和=总和+读数;
//平均数的计算
平均值=总和/项目数;
}

我会读入一个字符串,然后将其转换为整数。用流替换cin

请注意,stoi具有一些可能令人惊讶的特性,例如支持十六进制


请阅读:欢迎来到堆栈溢出@πάνταῥεῖ 谢谢,这很有帮助。
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
  }
}