如何检查用户是否输入足够的项目

How to check if user input enough items?

本文关键字:输入 项目 是否 用户 何检查 检查      更新时间:2023-10-16

假设我有用户输入这些变量:ID名称年龄

我使用while循环来获取用户输入,例如

while(cin){
cin >> ID >> name >> age;
do_stuff(ID, name, age);

}

但是如果在某个时刻用户只输入其中的一些变量,比如只输入ID和name, while循环应该立即结束,而不运行do_stuff()。我该怎么做呢,方法要快。谢谢你!

#include <iostream>
#include <string>
int main() {
        int ID, age;
        std::string name;
        while(std::cin.good()){
                if (std::cin >> ID && std::cin >> name && std::cin >> age) {
                        std::cout << ID << name << age << std::endl;
                }
        }
        return 0;
}

您可以通过使用stringstream和getline实现这一点,如下所示:

  #include <sstream>
  #include <string>
  int age = -1; //assume you init age  as -1 and age is integer type
  stringstream ss;
  while (getline(cin,line))
  {
     age = -1;
     ss.clear();
     ss << line;
     ss >> ID >> name >>age;
    if (age ==-1)  //if no age is parsed from input line, break the while loop
    {
       cout << "no age is contained in input line" <<endl;
       break;
    }
    do_stuff(ID,name, age)
  }

这应该可以工作,但可能存在更好的解决方案。