例如,我需要接受不同直线上的两个矩形的尺寸。
我这样试过:
int a1, b1, a2, b2;
char c;
cin >> a1 >> b1;
cin >> c >> a2 >> b2;
最佳答案
所以您希望用户以这种方式输入这 4 个整数:
-10 0
30 40
并且您想拒绝所有其他格式的输入...
换句话说,输入必须包括:
4
int
整数2
' '
个空格2
'\n'
换行符
您可以修改我将要讨论的逻辑以根据需要调整这些参数。
这更像是一个解决问题的任务。无论如何,由于某些原因您不想使用 getline
,您将不得不自己管理大部分输入处理。
这是我的看法:
按字符读取输入字符 (
char ch
),直到收到四个单独的(由空格或换行符分隔)输入(可以是任何东西,包括 void,之后可以进行验证)。使用std::stringstream
(stringstream input
) 读取整个输入;随着我们的进行,它将使输入验证更加容易。有两个变量(unsigned spaceCount = 0;
和unsigned newlineCount = 0;
)来控制循环终止。while (newlineCount + spaceCount != 4) { ch = cin.get(); input << ch; if (ch == ' ') ++spaceCount; if (ch == '\n') ++newlineCount; }
在继续之前,您需要一个像
bool isInt(string num)
这样的函数来检查给定的字符串是否是一个整数。你可以根据自己的需要自己制作一个。 Stackoverflow 已经有一个线程:How to determine if a string is a number with C++?仅当字符串适合int
时,该函数才必须返回 true。然后您可以检查用户输入是否有隐藏的 gem 、非输入或垃圾邮件:
bool inputFormatCorrect = true; if (spaceCount == 2 && newlineCount == 2) { stringstream tmpInput; string tmpStr; tmpInput << input.str(); for (int i = 0; i < 4; ++i) { tmpInput >> tmpStr; if (!isInt(tmpStr)) { inputFormatCorrect = false; break; } } } else { inputFormatCorrect = false; }
检查完成后,您可以提取并显示您的整数 (
int a1, b1, a2, b2;
):if (inputFormatCorrect) { input >> a1 >> b1 >> a2 >> b2; cout << "a1 = " << a1 << ", b1 = " << b1 << ", a2 = " << a2 << ", b2 = " << b2; } else { cout << "I don't like your style of inputting..."; }
将它们放在一起:
Live Demo
而且我不太确定你是否也想限制空格,但你可以修改逻辑以删除所有出现的spaceCount
并更改读取循环条件while (newlineCount != 2)
如果需要的话。
所以,你真的想让事情变得复杂吗?我们拥有标准输入是有原因的。
我还是喜欢
cin >> a1 >> b1 >> a2 >> b2;
与其让用户感到为难:
关于c++ - 如何在不使用 getline() 的情况下接受不同行中的整数输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61692788/