c++ - 显示 vector 的元素

标签 c++

我正在尝试学习 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。如果有人告诉我哪里错了,我将不胜感激。

最佳答案

我推荐以下策略。

  1. 循环逐行读取文件/cin的内容。
  2. 如果该行包含停止指令,则停止循环。
  3. 使用 std::istringstream 从行中提取必要的数据。
  4. 如果提取数据时出现错误,请处理该错误。否则,请使用数据。

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/

相关文章:

c++ - noreturn 的意义何在?

c++ - native c++ 指针(例如 uint16 *)上 std::find() 的替代或增强

c++ - 使用 Qt c++ 在 Windows Surface pro 上获取加速度计数据?

c++ - 模板版和非模板版功能相同

c++ - QSocketNotifier : Socket notifiers cannot be enabled or disabled from another thread

c++ - 用 C++ 创建一个基本的 UDP 聊天程序

c++ - 如何使用 const/nonconst 指针/引用参数模板化函数

c++ - Bison Flex 链接问题

c++ - 深度复制到堆上的 c 数组 block

c++ - 如何在Qt中定期调用一个函数?