当我使用 cin 进行两个输入时,如何接受一个输入

How do I take in one input when I use cin for two inputs?

本文关键字:输入 何接受 一个 两个 cin      更新时间:2023-10-16

所以在大多数输入行中,我必须取一个整数,然后是空格,然后是一个字符串,如'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
    }
}