1

I'm trying to write a program that reads a file and calculates things like averages and max number and all that. The program works fine when there are only numerical values in the file but the program needs to be able to read in values until it encounters any non numerical value and compute the average and so on from the values it had read before it encountered a character. I have no idea how to go about that.

I tried an if statement using isAlpha but the program just gets stuck after I input the name of the file it's looking into if there is a non-numerical value in the file.

//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;


    }
Matthieu Brucher
  • 19,950
  • 6
  • 30
  • 49

1 Answers1

1

I would read in a string and then convert it to an integer. Replace cin with your stream.

Beware that stoi has some potentially surprising properties e.g. support for hex

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
  }
}
sudo rm -rf slash
  • 856
  • 1
  • 11
  • 27