1

I am a beginner in c++ coding and i have an assignment for my class. I am trying to read the first line of integers separated by spaces 2 spaces in the file (cannot use arrays or vectors). I have seen many tutorials telling me to use getline () and simply reading each and every integer and storing it into its own variable, but neither method has been working for me. Does anybody have a way to read in the first line with a while loop and have it so that I can then find the maximum and minimum values from the line, as well as calculate the average EXCLUDING the maximum and minimum values?

sample input i was instructed to analyze is as follows

5  7  9  8  7
30032
51111
52000
42000
9  8  6  3  7
70000
23765
24000
41004

Here is what I have so far.

{
    void PrintIntro (); {
        cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl;
        cout << "Welcome to Tallahassee Idol!  Where Stars are Born!!!" <<endl;
        cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-" <<endl<<endl;
    }

    /*******************************************************************************/

    void OpenFile (); {

        ifstream myFile;                // filestream for input file 
        string fileName;                // string for user to input filename

        cout <<"Enter a valid filename (no blanks please): ";
        cin >> fileName;

        myFile.open(fileName);

        while (!myFile) {
            cout << "Please re-enter a valid filename: "<<endl<<endl;
            cin >> fileName;
            myFile.open(fileName);
              
        }
    }

    /*******************************************************************************/

    void GetJudgeScore1 (); {
        ifstream myFile;                    // filestream for input file 
        string fileName;                    // string for user to input filename

        int player1Total = 0;               // total score for player 1
        int player1Average = 0;             // average for player 1
        int highScore1 = 0;                 // highest score to be excluded
        int lowScore1 = 100;                // lowest score to be excluded
        const int judgeAmt = 5;

        

        cout << "Processing Judge Data for Contestant 1" <<endl;
        cout << "=====================================" <<endl;
        cout << "Judge scores are: ";

        if (myFile.is_open()){              // if the file is open, read data in
                                            // here is where i ran into problems
            }
        }              
        
    
        return 0;
    }
Wyatt d
  • 21
  • 1
  • 3
  • Use getline into a string. then istringstream to parse out the integers on that line that you read into the string. See option #2 in this answer: [https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c/7868998#7868998](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c/7868998#7868998) – drescherjm Feb 25 '22 at 15:30
  • Also when you ask a question at StackOverflow you need to focus on a single problem in the code you have written. Reading input has nothing at all to do with finding the maximum or other statistics. That should be a totally different question since its a totally different problem. In both cases your question will not be well received if you don't show an attempt to solve the problem you ask to be solved. We are not here to do your homework for you. We are here to help you with a problem in your code for the benefit of future readers who may have the same 1 problem in the future. – drescherjm Feb 25 '22 at 15:32
  • 1
    It's a bit unclear what your problem is. If you can do `cin >> fileName;` what stops you from also doing `myFile >> number;` ? And perhaps repeat. To find minimum and maximum values, the standard library has a whole set of `min` and `max` functions. Try those! – BoP Feb 25 '22 at 15:47
  • sorry for being unclear in my post i am new to a lot of this stuff. My issue is that I don't know how to read in the first line of input in a way so that i can print out the data and then use it for statistical analysis i.e. finding the max, min etc. I dont know what code to put after "if (myFile.is_open" so that i can read the data. – Wyatt d Feb 25 '22 at 15:50
  • If you are required to calculate the statistics with no vector, array, linked list and only individual variables you will need to store the current max, min, and sum (of all values except the min and max) and the number of values read. While you are reading the input when you find a new min or max add the value of the old min or max to the sum. – drescherjm Feb 25 '22 at 16:22

2 Answers2

2

You can use a combination of std::string and std::istringstream and std::getline to iterate through the different integers in the line as shown below. The explanation is given in the comments.


#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
#include <climits>
int main()
{
    std::string line;//for storing a single line 
     
    int max = INT_MIN, min = INT_MAX, num = 0, count =0;
    std::ifstream inFile("input.txt");
    if(inFile)
    {
        while(std::getline(inFile, line))//go line by line
        {
            
            std::istringstream ss(line);
            while(ss >> num)//go number by number 
            {
                if(num > max)
                {
                    max = num;//update the maximum
                }
                if(num < min)
                {
                    min = num; //update the minimum
                }
                ++count;
                
            }
            //you can add an if statement here to print the result only if count > 1
            std::cout<<"max is: "<<max<<std::endl;
            std::cout<<"min is: "<<min<<std::endl;
        
           
            count = 0;        //make the count 0 for next iteration
            max   = INT_MIN; //reset max 
            min   = INT_MAX; //reset min
            std::cout<<"----------------------"<<std::endl;
        }
    }
    else 
    {
        std::cout<<"input file cannot be opened"<<std::endl;
    }
    return 0;
}

The output of the above program can be seen here:

max is: 9
min is: 5
----------------------
max is: 30032
min is: 30032
----------------------
max is: 51111
min is: 51111
----------------------
max is: 52000
min is: 52000
----------------------
max is: 42000
min is: 42000
----------------------
max is: 9
min is: 3
----------------------
max is: 70000
min is: 70000
----------------------
max is: 23765
min is: 23765
----------------------
max is: 24000
min is: 24000
----------------------
max is: 41004
min is: 41004
----------------------

Method 2

By looking at your comments below, it seems you do not want(or not allowed) to use climits. The below program shows how you can find the max and min without using climits.

#include <iostream>
#include<string>
#include <sstream>
#include <fstream>
int main()
{
    std::string line;//for storing a single line 
    std::string numWord; //for storing a single number as std::string 
    int max = 0, min = 0, num = 0, count =0;
    std::ifstream inFile("input.txt");
    if(inFile)
    {
        while(std::getline(inFile, line))//go line by line
        {

            std::istringstream ss(line);
            
            //read the first number in max and min 
            ss >> max; 
            min = max;
            
            while(ss >> num)//go number by number 
            {
                if(num > max)
                {
                    max = num;//update the maximum
                }
                if(num < min)
                {
                    min = num; //update the minimum
                }
                ++count;

            }
            //you can add an if statement here to print the result only if count > 1
            std::cout<<"max is: "<<max<<std::endl;
            std::cout<<"min is: "<<min<<std::endl;


            count = 0;        //make the count 0 for next iteration
            max   = 0; //reset max 
            min   = 0; //reset min
            std::cout<<"----------------------"<<std::endl;
        }
    }
    else 
    {
        std::cout<<"input file cannot be opened"<<std::endl;
    }
    return 0;
}

The output of the above program can be seen here.

Note

Since this is a homework problem, i am skipping finding out the average of the numbers so that you can modify the above program accordingly and so that i don't give the whole solution myself. Note that since your requirement is that not to use std::vector or arrays, i haven't used them in my program.

Hint:(for finding average) Add a variable called sum or average and add value of variable num to it inside the while loop.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • thank you for the feedback! is there any way to make the loop just stop after reading the first line? – Wyatt d Mar 01 '22 at 18:12
  • @Wyattd You're welcome. If you want to only read the first line then just remove the `while` from the statement `while(std::getline(inFile, line))`. See [DEMO](https://onlinegdb.com/80uFXsHZm). In the above mentioned demo, i have removed the main while loop and so we read only the first line as you want. If this answer helped you solving your issue, can you mark this answer as correct by clicking on the check/tick mark at the left side of the answer. – Jason Mar 01 '22 at 18:32
  • If you make the `while(std::getline(inFile, line)) {` into `if(std::getline(inFile, line)) {` you have it read only the first line and calculate stats on that 1 line. – drescherjm Mar 01 '22 at 19:57
  • while this method works, I am not allowed to use the library . is there any other way to find the max and min from the line? – Wyatt d Mar 01 '22 at 21:31
  • Anoop, I used your method and removed the while loop and replaced it with an if statement. It resultantly outputted the max is: 2147483647 the min is: -2147483648, which is not correct. How do i solve this issue? – Wyatt d Mar 01 '22 at 22:53
  • 1
    @Wyattd If you replace the `while` with an `if` then you'll get the correct output. See [DEMO](https://onlinegdb.com/o2qgdtWir). In the mentioned demo link, i have made only 1 change which is that i have replaced `while` with `if` and the program reads only the first line. – Jason Mar 02 '22 at 03:24
  • @Wyattd [Here](https://onlinegdb.com/chQmy3mW9) is the [DEMO](https://onlinegdb.com/chQmy3mW9) without using `climits`. I have added how you can do this without using `climits` in my answer as well. Check out my edited answer(method 2 in particular). – Jason Mar 02 '22 at 03:40
1

I am unsure as to what you mean by "cannot use arrays or vectors." The following code will read each line and save it to a string, convert it, and add it to an integer array, for easier storage. You could use multiple variables instead.

#include <fstream>
#include <string>

void getData() {
   std::string output;
   int i = 0, data[10]; // Pre-defined array size, looking at your data set.
   std::ifstream myFile;

   myFile.open("Path\\To\\Your\\File.txt", ios::in);
   while(getline(myFile, output))
   {
       data[i] = std::stoi(output);
       i++;
       std::cout << data[i] << "\n";
   }
   myFile.close();
}

Output:

57987

30032

51111

52000

42000

98637

70000

23765

24000

41004

  • my teacher will not allow us to use arrays or vectors that is what i meant. She is a very harsh grader and has strict guidelines on how we can code including only allowing us to use namespace std:: and other annoying hoops to jump through. – Wyatt d Feb 25 '22 at 16:21
  • I commented on how I think you could do that in the question comments. Think about this with a paper and pen and someone calling out numbers where you are not permitted to write the numbers down only you are allowed to keep the current min, max, # of values and sum of all but min and max. – drescherjm Feb 25 '22 at 16:31
  • Well, in that case, you could just use one integer variable which is passed to a math function you can write. You could have a `sum` variable which has something such as `sum += data` and divide it by the iterations afterwards. Your question was, however, in regards to reading from a text file, not the math behind this. – Anonymous_Codesman Feb 25 '22 at 16:38