c++ - 当我将 cin 用于两个输入时,如何接收一个输入?
问题描述
因此,在大多数输入行中,我必须取一个整数,然后是空格,然后是一个字符串,例如“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
for时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.\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 进行分组。^
$
?:
推荐阅读
- fabricjs - fabricjs toSVG 在新情况下和从 JSON 加载设计时为带有 clipto 的图像提供不同的输出
- javascript - Vaadin TextArea 将起始行号设置为 1
- javascript - 如何仅将烧瓶路由用于调用函数而不在浏览器中重定向
- divi - 如何在 Divi 的自定义页脚中排除特定页面?
- oracle - PLS-00404:光标列表以避免重复列请求别名
- asp.net-core - 为什么 Postgresql-12 的连接池已经耗尽?
- android - Flutter:只有在登录成功后按下返回按钮时才会出现主屏幕
- elasticsearch - Bulk API 中 ES 中的 ES 日志摄取是否有限制?
- kubernetes - 显示关闭 pod 的 GKE GUI 概览
- java - Java 中的 java Files.lines 和 Files.newBufferedReader().lines 之间的实际区别是什么?