0

I have the following file stored in a string vector. ratingsTiny.txt...

Jesse
-3 5 -3 0 -1 -1 0 0 5 
Shakea
5 0 5 0 5 0 0 0 1 
Batool
5 -5 0 0 0 0 0 -3 -5 
Muhammad
0 0 0 -5 0 -3 0 0 0 
Maria
5 0 5 0 0 0 0 1 0 
Alex
5 0 0 5 0 5 5 1 0 
Riley
-5 3 -5 0 -1 0 0 0 3 

My goal is extract the numbers, preferably column wise, to add them together and get an average rating for each column among the 7 users.

My closest attempt is below, but I can only print the first column and I can't figure out how to iterate through the entirety of the rows to get the rest of the integers.

Any help is very much appreciated.

        ourvector<string> ratings; 

        for (int i = 1; i < ratings.size(); i += 2){
        int num = atoi(ratings[i].c_str()); 
        intRatings.push_back(num); 
        cout << num << endl; 
    }
Nicholas
  • 89
  • 6
  • Not sure what `ourvector` is, but I'm guessing `ourvector.size() = 0` when it is first created. – 001 Jan 18 '21 at 20:09
  • Here's a simple way to figure out how to do this, and it never fails to work. Just take out a blank sheet of paper. Write down using short, simple sentences in plain English, a step-by-step process of doing this. When done, [call your rubber duck for an appointment](https://en.wikipedia.org/wiki/Rubber_duck_debugging). Generally, we don't write code for other people, on Stackoverflow. We always refer such questions to your rubber duck. After your rubber duck approves your proposed plan of action, simply take what you've written down and translate it directly into C++. Mission accomplished! – Sam Varshavchik Jan 18 '21 at 20:09
  • If you initialised the vector to contain the right number of entries, you might be able to use it to store the current sum for each of your columns as you move through the input. For each row of input you would be adding to the existing per-column sum in your vector. By also keeping track of the number of rows you’ve processed, you could calculate the average. – Chris Pearce Jan 18 '21 at 20:10
  • [Option 2 of this answer](https://stackoverflow.com/a/7868998/4581301) provides a reading technique you may find helpful. – user4581301 Jan 18 '21 at 20:10
  • @JohnnyMopp ourvector is just an implementation of the standard vector class. My code is a little misleading though. For the sake of brevity, I left out the function that actually stores the file into the ratings vector. Ourvector.size() = 14, each element contains a string line of the ratings file – Nicholas Jan 18 '21 at 20:22
  • 2
    Then you can use `stringstream` as mentioned in a previous comment: `int num; std::istringstream iss(ratings[i]); while (iss >> num) intRatings.push_back(num);` – 001 Jan 18 '21 at 20:25
  • Or just construct the vector from an istream_iterator range. Let it do the loop for you. – WhozCraig Jan 18 '21 at 20:31
  • Please provide a [mre]. – Yunnosch Jan 18 '21 at 21:24

0 Answers0