如何检查用户是否输入足够的项目
How to check if user input enough items?
假设我有用户输入这些变量: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)
}
这应该可以工作,但可能存在更好的解决方案。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- 欧拉项目#8:C++错误的答案(为一个小的炮制输入给出正确的答案)
- 我的 Visual c++ 托管单元测试项目未读取输入文件
- C++简单的暴力项目密码输入方法
- 默认构造函数 Eclipse 项目中的用户输入
- 基于用户输入(C 学校项目)计算
- 我正在编写一个代码,该代码从用户那里为公司中的五个项目输入数量
- win32 C++项目中的输入超时
- 输入验证用于选择用字符的项目,通过CIN.FAIL遇到错误
- 从 excel 到 cpp 项目的输入和输出
- 使用git管理的c++项目在不同的机器上使用相同的输入以不同的方式运行
- 如何在C++中将长输入拆分为多个项目
- 试图编译一个qt项目,在不同的地方得到输入/输出错误
- 如何使用循环和数组将所有输入的项目代码(具有相应的值)加起来
- 链接器输入|将库添加到多个项目
- 如何检查用户是否输入足够的项目