什么时候应该std::cin.getline()使用?它有什么不同std::cin?
例如,
#include <iostream>
int main() {
unsigned n{};
std::cin >> n;
std::cout << n << ' ' << (bool)std::cin << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输入时-1,clang 6.0.0输出,0 0而gcc 7.2.0输出4294967295 1.我想知道谁是对的.或者两者都是正确的标准没有指定这个?如果失败,我认为(bool)std::cin被评估为假.clang 6.0.0也输入失败-0.
假设我们有一个代码:
int main()
{
char a[10];
for(int i = 0; i < 10; i++)
{
cin>>a[i];
if(a[i] == ' ')
cout<<"It is a space!!!"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何从标准输入中删除空格符号?如果你写空间,程序会忽略!:(是否有任何符号组合(例如'\ s'或类似的东西),这意味着我可以从我的代码的标准输入中使用"空间"?
我看起来无济于事,我担心这可能是一个简单的问题,没有人敢问它.
可以从一行中的标准输入输入多个东西吗?我是说这个:
float a, b;
char c;
// It is safe to assume a, b, c will be in float, float, char form?
cin >> a >> b >> c;
Run Code Online (Sandbox Code Playgroud) 这个特定的行在cin.ignore(numeric_limits<streamsize>::max(), '\n')C++编程中意味着什么?这实际上忽略了用户的最后输入吗?
我是C++的新手,并且一直在学习这样的东西:
cout << "My age is: ";
cin >> age;
Run Code Online (Sandbox Code Playgroud)
和cin一起乱搞,我遇到了障碍.
说我想写"我已经x岁了!".
"x"是cin >>年龄;
我写这样的代码.
cout << "I am ";
cin >> age;
cout << "years old!";
Run Code Online (Sandbox Code Playgroud)
障碍是这会产生换行符.
我不希望换行.
我怎么能把这一切留在一条线上?
在下面的循环中,如果我们输入字符作为cin输入而不是预期的数字,那么它将进入无限循环.有人可以向我解释为什么会这样吗?
当我们使用时cin,如果输入不是数字,那么有没有办法检测到这一点以避免上述问题?
unsigned long ul_x1, ul_x2;
while (1)
{
cin >> ul_x1 >> ul_x2;
cout << "ux_x1 is " << ul_x1 << endl << "ul_x2 is " << ul_x2 << endl;
}
Run Code Online (Sandbox Code Playgroud) 我在我的mac/xcode上编译了这个代码,没有任何问题.我在学校用linux上的g ++编译它,我得到这些错误:
:'numeric_limits'不是std的成员
:'>'标记之前的预期primary-expression
:没有用于调用'max()'的匹配函数
#include <iostream>
#include <cstdlib>
using namespace std;
int GetIntegerInput(int lower, int upper)
{
int integer = -1;
do
{
cin >> integer;
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n'); //errors here
}while (integer < lower || integer > upper);
return integer;
}
Run Code Online (Sandbox Code Playgroud)
我猜对了也许我必须加一个额外的标题.如果我带走了std ::它只是给了我一个类似的错误
'numeric_limits'未在此范围内声明
我如何检查输入是否真的是双倍的?
double x;
while (1) {
cout << '>';
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}
//do other stuff...
Run Code Online (Sandbox Code Playgroud)
上面的代码无限输出Invalid Input!语句,因此它不会提示输入其他内容.我想提示输入,检查它是否合法...如果它是双,继续......如果它不是双,再次提示.
有任何想法吗?