Cin 需要 2 个输入
Cin requires 2 inputs
我正在尝试创建一个函数来确保数字大于零,但是每当用户不输入大于零的数字时,他们必须输入两次值才能继续代码。请帮忙!
int userInput()
{
int goAhead = 0;
int a;
while (goAhead == 0)
{
cin >> a;
if(a <= 0 )
{
cout << "The can not be less than or equal to zero, enter another value: " << endl;
cin >> a;
cin.ignore();
}
else
{
// enter code here
goAhead = 1;
}
return a;
}
}
我希望
它有所帮助:
int userInput()
{
int a = 0;
while(a <= 0) {
cout << "Enter value greater than zero: " << endl;
cin >> a ;
if(a <= 0)
cout << "Input incorrect. Please try again " << endl;
}
return a;
}
int userInput()
{
int a;
int tries = 2; // this will count down to 0, which then return anything you want as an invalid answer
do
{
cout << "enter value: ";
cin >> a;
if( a > 0 )
{
return a;
}
else
{
if(--tries > 0)
{
cout << "The can not be less than or equal to zero" << endl;
}
else
{
cout << "returning -1" << endl;
return -1;
}
}
}while (true);
}
尝试使用 while 循环
cin>>a;
while(a<=0)
{
System.out.println("Please enter again");
cin>>a;
}
如果您只想再增加 2 次,只需添加一个计数器。
我希望它有所帮助。
这应该做你想做的事情
int userInput()
{
int a;
cin >> a;
while(a <= 0 )
{
cout << "The can not be less than or equal to zero, enter another value: "<< endl;
cin >> a;
cin.ignore();
}
return a;
}
相关文章:
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- C++:用户输入会产生不需要的行为
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 需要有关运行具有输入类型的编译器的帮助
- C++ - 有什么方法可以将输入插入缓冲区/停止 cin.忽略需要输入?
- Cin 需要两个输入
- tensorflow:transpose需要一个大小为1的向量.但是输入(1)是大小为2的向量
- 我的代码看起来不错,但某些输入会导致不需要的输出
- 对需要双精度数组和结构作为输入C++ DLL 函数的 C# 调用
- 我需要制作一个程序来计算用户输入的特定数量的数字
- C++使用二维数组的程序,该数组要求用户输入两次.它需要将这些输入显示为输出
- 位集<10>和位集<2>(输入[i])的差异,需要解释
- 我需要编写一个代码,从用户那里获取输入(句子)并停止在@处
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 为什么 while 循环不需要用户在 C++ 中输入
- 防止在流中输入不需要的价值
- 不只打印所有字母,而是需要在输入后打印出每个字母
- 需要帮助传递数组和输入数组
- 输入需要我的程序结构/设计