【发布时间】:2017-01-05 18:37:35
【问题描述】:
我试图确保我的输入字符串格式正确(格式正确 XXX-X-XXX ),但我不想使用 char temp[255] 和 cin.getline 组合。
到目前为止,我已经设法“捕获”了除此之外的所有异常:
输入车牌:shjkf 22h 23jfh3kfh jkfhsdj h2j h2k 123-A-456
假设 regPlate 将从输入中获取所有字符串,包括最后格式化的正确字符串,并将打印字符串。这是不正确的。读取第一个字符串后,它应该打印 Bad input 以及需要删除之后的所有内容。
我尝试过使用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");
}
【问题讨论】:
-
您不需要检查大小是否小于
9和大于9。只需检查一次大小不等于9。 -
至于你的问题,你是不是在找
std::getline? -
@Someprogrammerdude "但我不想使用 char temp[255] 和 cin.getline 组合。"
-
@BrunoFerreira
std::getline和std::istream::getline是两个不同的东西。 -
@Someprogrammerdude 我想你可以假设 OP 根本不想要任何
getlines。
标签: c++ string format stdstring istream