odido
odido

Reputation: 21

Display elements of vectors

I'm trying to learn C++ as my first language and I want to apologies for my silly question. I want to fill two vectors with integers and display their sizes, but every time when check their number of elements I receive unexpected results.Perhaps I'm missing something fundamental.Here is my code:

`

#include<vector>
#include<string>
#include<iostream>

using namespace std;

int main(int argc, char** argv) {

    string stop;
    vector <int>adults;
    vector <int>kids;
    int  int_var;


    while (getline(cin, stop) && stop != "stop") {

        cin>>int_var;


        if (int_var > 16) {
            adults.push_back(int_var);

        } 
         else if (int_var <= 16) {
            kids.push_back(int_var);
        }

    }
    cout << "Number of adults: " << adults.size() << endl;
    cout << "Number of kids: " << kids.size() << endl;



}

`

Every time in this crappy code the first value of int_var goes to second vector where must contain only numbers >16 .I'd be grateful if someone tells me where I'm wrong.

Upvotes: 2

Views: 81

Answers (2)

Fred Larson
Fred Larson

Reputation: 62073

Here's an alternate solution using std::stoi, as my comment suggested:

#include<vector>
#include<string>
#include<iostream>

int main(/*int argc, char** argv*/)
{

    std::string entry;
    std::vector<int> adults;
    std::vector<int> kids;
    int int_var;

    while (std::getline(std::cin, entry) && entry != "stop")
    {
        try
        {
            int_var = std::stoi(entry);

            if (int_var > 16)
            {
                adults.push_back(int_var);

            }
            else
            {
                kids.push_back(int_var);
            }
        }
        catch (const std::exception& /*ex*/)
        {
            std::cout << "Oops, that wasn't a valid number. Try again.\n";
        }
    }

    std::cout << "Number of adults: " << adults.size() << '\n';
    std::cout << "Number of kids: " << kids.size() << '\n';
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206607

I recommend the following strategy.

  1. Read the contents of the file/cin line by line in a loop.
  2. If the line contains the instructions to stop, stop the loop.
  3. Extract the necessary data from the line by using a std::istringstream.
  4. If there is an error in extracting the data, deal with the error. Otherwise, use the data.

std::string line;
while (getline(std::cin, line) )
{
   if ( line == "stop")
   {
      break;
   }

   std::istringstream str(line);

   if ( str >> int_var )
   {
      // Data extraction was successful. Use the data
      if (int_var > 16)
      {
         adults.push_back(int_var);
      } 
      else if (int_var <= 16)
      {
         kids.push_back(int_var);
      }
   }
   else 
   {
      // Error extracting the data. Deal with the error.
      // You can choose to ignore the input or exit with failure.
   }
}

Upvotes: 2

Related Questions