Reputation: 21
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
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
Reputation: 206607
I recommend the following strategy.
std::istringstream
.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