c++ - 如何从文本文件中读取数值直到遇到 char 类型?

标签 c++

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

我尝试了一个使用 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/

相关文章:

c++ - 使用 goto 传递 POD 堆栈变量时的范围和生命周期

c++ - 强制 cpp_dec_float 向下舍入

c++ - 将字符串文字传递给采用 std::string& 的函数

c++ - 绘图对象 - 更好的类设计?

c++ - 使用 select() 从多个使用 UDP 套接字的对等方接收,同时从 STDIN 获取用户输入

c++ - 带有字符串变量指令的 C/C++ 内联汇编程序

c++ - 关于C++类的几个问题

c++ - 基类和派生类中的模板成员之间的重载解析

c++ - 任何人都知道如何修复编译错误 : LNK2005?(内部源代码)

c++ - 在构造函数初始化程序中复制初始化?