我正在尝试学习 C++ 作为我的第一语言,我想为我的愚蠢问题道歉。 我想用整数填充两个 vector 并显示它们的大小,但是每次检查它们的元素数量时我都会收到意外的结果。也许我错过了一些基本的东西。这是我的代码:
`
#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;
}
`
每次在这个蹩脚的代码中,int_var的第一个值都会转到第二个 vector ,其中必须仅包含数字> 16。如果有人告诉我哪里错了,我将不胜感激。
最佳答案
我推荐以下策略。
- 循环逐行读取文件/cin的内容。
- 如果该行包含停止指令,则停止循环。
- 使用
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.
}
}
关于c++ - 显示 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54355486/