繁体   English   中英

确保在C ++中正确输入字符串

[英]Assure correct string input in C++

我试图确保输入字符串的格式正确(格式正确XXX-X-XXX),但是我不想使用char temp [255]和cin.getline组合。

到目前为止,我已经设法“捕获”了除此以外的所有异常:

输入车牌 :shjkf 22h 23jfh3kfh jkfhsdj h2j h2k 123-A-456

假设regPlate将从输入中获取所有字符串,包括结尾处正确格式化的字符串,然后将其打印出来,这是不正确的。 读取第一个字符串后,应打印错误输入,并且需要删除所有内容。

我尝试使用cin.clear()cin.ignore()等。 在我的if函数中,但是没有结果。

void main()
{
    std::string regPlate;
    do
    {
        cout << "Enter registration plate: ";
        cin >> regPlate;
        if (regPlate.size() < 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-' || regPlate.size() > 9)
        {
            cout << "Bad entry" << endl;

        }
    } while (regPlate.size() < 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-' || regPlate.size() > 9);
    cout << endl << regPlate << endl;

    system("pause");
}

一会儿循环会起作用,也许是这样的:

int main(){
    string regPlate;
    while(regPlate.size() != 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-'){
        cout << "Enter registration plate: " << endl;
        cin >> regPlate;
    }
    cout << regPlate;
    return 0;
}

使用您提供的示例(有一些假设),我运行了您的代码,它似乎按预期工作。 这是我运行的,包括标头。

#include <string>
#include <iostream>

using namespace std;

void main()
{
   string regPlate;
   do
   {
       cout << "Enter registration plate: ";
       cin >> regPlate;
       if (regPlate.size() != 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-')
       {
          cout << "Bad entry" << endl;

       }
   } while (regPlate.size() != 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-');
   cout << endl << regPlate << endl;

   system("pause");
}

我收到的输出是:

Enter registration plate: shjkf 22h 23jfh3kfh jkfhsdj h2j h2k 123-A-456
Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: Bad Entry
Enter registration plate: 
123-A-456

我还手动键入了您列出的所有值,并且它似乎也可以正常工作。

感谢@Someprogrammerdude,我设法解决了这个问题。

我唯一要做的是使用std::getline(cin,regPlate)代替std::cin>>regPlate

std::string regPlate;
    do
    {
        cout << "Enter registration plate: ";
        std::getline(cin, regPlate);
        if (regPlate.size() != 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-')
        {
            cout << "Bad entry" << endl;

        }
    } while (regPlate.size() != 9 || regPlate.at(3) != '-' || regPlate.at(5) != '-');
    cout << regPlate << endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM