当我使用 cin 进行两个输入时,如何接受一个输入
How do I take in one input when I use cin for two inputs?
所以在大多数输入行中,我必须取一个整数,然后是空格,然后是一个字符串,如'3 kldj'或'5 sfA',但要表示停止,我只需要取整数0。使用 cin>> intVar>> stringVar;它总是一直在寻找 stringVar,并且不接受 0。当字符串为空时,如何只接受 N?
if (!(cin>>N>>input)) {
break;
cin.clear();
}
我已经试过了,但它不起作用。这是在一个 while 循环中,所以我用它来打破它。N 是整数,输入是字符串。
OP 您可能应该放弃在一个输入行中尝试这样做。 将其一分为二:
int N;
std::string input;
while (true) {
std::cin >> N;
if (N == 0) {
break;
}
std::cin >> input;
}
这应该可以正常工作。当用户输入0
N
时,循环退出。但是,如果您必须执行一条输入行,您将不得不采取艰难的方式。意思是使用regex
。它允许您解析输入并始终保证某种行为。
#include <regex>
#include <iostream>
#include <string>
#include <vector>
#include <utility> //std::pair
int main() {
const std::regex regex{ "^(?:([0-9]+) ([a-zA-Z]+))|0$" };
std::smatch smatch;
std::vector<std::pair<int, std::string>> content;
std::cout << "type in numbers + word (e.g. "5 wasd"). single "0" to exit.nn";
std::string input;
while (true) {
bool match = false;
while (!match) {
std::getline(std::cin, input);
match = std::regex_match(input, smatch, regex);
if (!match) {
std::cout << "> invalid input. try againn";
}
}
if (input == "0") {
break;
}
auto number = std::stoi(smatch.str(1));
auto word = smatch.str(2);
content.push_back(std::make_pair(number, word));
}
std::cout << "nyour input was:n[";
for (unsigned i = 0u; i < content.size(); ++i) {
if (i) std::cout << ", ";
std::cout << '{' << content[i].first << ", " << content[i].second << '}';
}
std::cout << "]n";
}
示例运行:
type in numbers + word (e.g. "5 wasd"). single "0" to exit.
5 asdf
12345 longer
hello
> invalid input. try again
5
> invalid input. try again
0
your input was:
[{5, asdf}, {12345, longer}]
^(?:([0-9]+) ([a-zA-Z]+))|0$
解释:
1
"([0-9]+)"
- 捕获任何(非零)位数2
" "
- 单个空间3
"([a-zA-Z]+)"
- 捕获任意(非零)数量的 A-Z 或 A-Z 字符
整个事情的组织方式(?: /*…*/)|0
这意味着由规则 1-3 组成的字符串或只有一个 \"0\" 与输入匹配。 ^
和$
表示输入的开始和结束。 ?:
使其能够在不捕获规则的情况下对规则 1-3 进行分组。
除非你也可以在"非终止"行的开头有零,否则将问题从"如果数字后面没有字符串,则只读取一个数字"转变为"读取一个数字然后读取一个字符串,但仅当数字不是 0 时"。
while (cin >> N && N != 0)
{
if (cin >> input)
{
// Handle input
}
}
相关文章:
- 在C++中,我如何接受不同于同一行的用户输入
- 为什么线程不接受此输入?
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- B不接受8作为输入的是什么?C++
- C++数组输入不接受一定数量的整数
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- C++ 我的开关格式中的循环不允许我显示菜单选项或接受输入?
- 该程序只接受 5 个输入,而我给出 n=8
- 斯堪夫不接受输入
- C++字符数组不接受超过 4 个字符的输入
- CIN不接受C++中带有空格的输入?
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- std::cin不接受输入
- 如何在C++中创建总是在循环中接受新输入的独立进程
- 我怎样才能接受输入作为双精度值并执行 IF ELSE 语句
- 如何接受可变的输入数字?
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 无法正确验证无效输入并接受带有C++的正确范围值
- c++二进制到十进制转换器输入只接受1或0