[英]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;
}
这应该工作得很好。 当用户为N
输入0
,循环退出。 但是,如果您必须在一行输入行中执行此操作,则您将不得不走上艰难的道路。 意思是使用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.\n\n";
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 again\n";
}
}
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]+)"
- 捕获任意(非零)数量的 az 或 AZ 字符
整个事情的组织像(?: /*…*/)|0
的意义要么组成的字符串规则1-3或只是一个\\“0 \\”的输入相匹配。 ^
和$
表示输入的开始和结束。 ?:
使其能够在不捕获它的情况下对规则 1-3 进行分组。
除非在“非终止”行的开头也可以有零,否则将问题从“如果数字后面没有字符串,则只读取一个数字”转变为“读取一个数字,然后读取一个字符串,但是仅当数字不为 0" 时。
while (cin >> N && N != 0)
{
if (cin >> input)
{
// Handle input
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.