首页 > 解决方案 > 当我将 cin 用于两个输入时,如何接收一个输入?

问题描述

因此,在大多数输入行中,我必须取一个整数,然后是空格,然后是一个字符串,例如“3 kldj”或“5 sfA”,但要表示停止,我只需要输入整数 0。使用 cin > > intVar >> stringVar; 它总是一直在寻找 stringVar 并且不只接受 0。当字符串为空时,我如何只接受 N?

if (!(cin>>N>>input)) {
    break;
    cin.clear();
}

我已经尝试过了,但它不起作用。这是在一个while循环内,所以我用它来打破它。N 是一个整数,输入是一个字符串。

标签: c++

解决方案


OP,您可能应该放弃在一个输入行中尝试此操作。把它分成两部分:

int N;
std::string input;

while (true) {
    std::cin >> N;
    if (N == 0) {
        break;
    }
    std::cin >> input;
}

这应该工作得很好。当用户输入0for时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 字符

整个事物的组织方式类似于由规则(?: /*…*/)|01-3组成的字符串只有一个 \"0\" 匹配输入。并指示输入的开始和结束。使其能够在不捕获规则的情况下对规则 1-3 进行分组。^$?:


推荐阅读