所以我开始学习c ++而且我已经编写了这个简单的程序,当用户输入错误的数字时它会提供再次尝试的选项,但是当用户输入任何字符时,它会提供再次尝试并直接退出程序的选项为什么会这样? `
#include<unistd.h>
#include<stdio.h>
int main(){
int a;
char b ,c;
start:
printf("INPUT ONLY NUMBER 1 : ");
scanf(" %d", &a);
if(a==1)
{
printf( " you entered correctly \n");
printf("do you want to try again? <Y> <N> \n");
scanf(" %c", &c);
if(c=='Y' ||c=='y')
{
goto start;
}
}
else {
sleep (1);
printf("wrong number , do you want to try again? <Y> <N> \n");
scanf(" %c" , &b);
}
if (b=='Y'||b=='y')
{
sleep(1);
goto start;
}
else
if(b=='n'||b=='N')
{
sleep(1);
printf("thank you and goodbye");
exit (1);
}
}
`
答案 0 :(得分:0)
scanf(" %d")
我打赌你的问题来自%d
之前的那个空间。试试scanf("%d")
。稍后相同:scanf("%c")
而不是scanf(" %c ")
。
无论如何,你的代码非常脏。这看起来像C,而不是C ++
不要试图成为一个疯子,但你应该正确地缩进并避免goto
所有方法。您的程序结构很简单,while
循环可以帮到您。您还应该避免明确调用exit(1)
。 exit
主要用于引发提前终止。在您的情况下,您的计划正常到达目的地,您应该使用main
功能return 0
退出。
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h> //Reauired to use boolean type in C
int main()
{
bool stop = false; //boolean type only has two states: true and false. Very useful for loops!
while(!stop) //Read as "While we don't need to stop, execute the loop's contents
{ //Much easier to read!
printf("INPUT ONLY NUMBER 1 : ");
scanf("%d", &a);
if(a == 1)
{
printf("you entered correctly \n");
printf("do you want to try again? <Y> <N>\n");
scanf("%c", &c);
if(c == 'N' || c == 'n')
{ //We only need to tell the loop when to stop
stop = true; //by setting stop to true
} //The loop's default behavior is to loop execution of its content
}
else
{
sleep(1);
printf("wrong number , do you want to try again? <Y> <N> \n");
scanf("%c" , &b);
if(b=='n'|| b=='N')
{
stop = true; //Same as above
}
sleep(1);
}
}
printf("thank you and goodbye");
return 0;
}
答案 1 :(得分:0)
你的scanf还有一些东西,有时候你可以把它清理干净,但你的代码似乎不起作用。
看一下这个问题就会遇到: http://c-faq.com/stdio/stdinflush2.html
这基本上告诉你,如果你的方法不起作用,那么你应该改变它。 希望这有帮助,你也问过你在那里的一个问题,所以:
#include <iostream>
int main(){
char input;
char try_again;
do {
std::cout << "INPUT ONLY NUMBER:";
std::cin >> input;
// http://en.cppreference.com/w/cpp/string/byte/isdigit
// does not return a bool, you can check that >0
if (std::isdigit(input)) {
// do what you want.
std::cout << "digit\n";
continue;
} else {
// you can as for more imput like:
std::cout << "Not a number, try again?(y/Y):";
std::cin >> try_again;
std::tolower(try_again);
if (try_again == 'y') {
continue; // will start the loop again.
} else {
break; // it will exit the loop.
}
}
} while(true);
return 0;
}
答案 2 :(得分:-1)
不要将输入读入int
类型的变量,而是读入char*
类型的变量。然后检查该值是否仅包含小数,如有必要,将其转换为int
。
(Ps。我不知道这些方法,但不应该谷歌他们)