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

问题描述 投票:0回答:4

我正在使用以下代码:

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

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

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

c++ cin
4个回答
0
投票

在你的代码中,如果你输入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;
}

0
投票

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


0
投票

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

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

0
投票

你可以用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循环停止。

© www.soinside.com 2019 - 2024. All rights reserved.