为 C++ cin 上的无效输入数量生成错误消息

Generate an error message for an invalid number of inputs on c++ cin

我正在使用以下代码:

string a, b, c;
cin >> a >> b >> c;

解释:如果用户输入,例如"hello new world hi" 则映射为 a='hello'b='new'c='world'"hi" 将被忽略 - 这就是问题所在!

我想要的是,如果参数数量错误(多于或少于 3 个),用户应该被强制再次输入(可能是通过错误消息)。

使用getline(cin, stringName) 输入遍历字符串后检查空格的索引,然后将其拆分为您想要的任何内容。

你甚至不需要声明三个字符串来存储。您可以使用 std::getline.

 std::string a;//,b,c; 
 std::getline(std::cin,a); //<< b << c; 
 std::cout <<a;

可以用std::getline读整行,然后用空格隔行。例如:

#include <string>
#include <vector>
#include <iostream>
// some code...
    std::string text;
    std::getline(std::cin, text);
    std::vector<std::string> words;
    int wordCount = 0;
    while (auto space = text.find_first_of(' '))
    {
        wordCount++;
        if (wordCount > 3)
        {
            std::cout << "Max 3 words!" << std::endl;
            break;
        }
        words.push_back(text.substr(0, space));
        text = text.substr(space + 1);  
    }

这样你将在向量 words 中最多包含 3 个单词,你可以通过首先调用 words[0] 来获取它们,等等。在第 4 次读取单词时打印错误并且 while循环停止。

在您的代码中,如果您输入 4 个单词,那么最后一个单词将存在于您机器上的某个位置(可能在键盘缓冲区中)。因此,如果您使用 cin 为另一个变量键入值,则最后一个单词将分配给该变量。因此,要检查用户是否输入错误,您可以执行以下操作:

#include<iostream>
#include<string>
#include <sstream>
using namespace std;

int main()
{
   string a, b, c;
   cin >> a >> b >> c;

   string check="";
   getline(cin, check);
   if (check != "")
   {
      cout << "input error,try again!";
   }
   return 0;
}