2010-10-23 55 views
0

我想使用下面的代码来检查输入。使用C命令在Visual C++中检查输入

#include <stdio.h> 
#include <iostream> 
#include <ctype.h> 

int main() 
    { 
    int number1; 

    puts("Enter number 1 please:"); 
    scanf_s("%d",&number1); 

    if (isdigit(number1)) 
    { 
     puts("Input is correct."); 

    } 
    else 
    { 
     puts("Your input is not correct. Enter a number please."); 
    } 

     std::cin.get(); 
     std::cin.get(); 


    } 

不幸的是,它并没有工作。我输入一个数字,我的回答是“您的输入不是...”。有问题的任何建议?

+0

为什么不使用cin和cout? – Puppy 2010-10-23 18:43:30

回答

0

你的问题是在使用isdigit。比较此代码:

int main() 
{ 
int number1; 

puts("Enter number 1 please:"); 
scanf_s("%d",&number1); 
printf("You entered %d\n", number1); 
if (isdigit(number1)) 
{ 
    puts("Input is correct."); 

} 
else 
{ 
    puts("Your input is not correct. Enter a number please."); 
} 

    std::cin.get(); 
    std::cin.get(); 


} 

当您输入一个有效的号码时,这反映在此号码的成功printf中。

您应该检查scanf函数的返回,不使用ISDIGIT,比如这个示例代码:

int main() 
{ 
int number1; 

puts("Enter number 1 please:"); 
if (scanf_s("%d",&number1))   
    puts("Input is correct."); 
else 
    puts("Your input is not correct. Enter a number please."); 

std::cin.get(); 
std::cin.get(); 
} 

我相信不止一个领域,你将需要更仔细地检查scanf函数的返回值而不仅仅是零或一个。

+0

谢谢。你的解决方案比我的更聪明。 – Ordo 2010-10-23 20:10:27

0

isdigit接受char类型的number1而不是int。 将number1替换为char类型将解决问题并报告正确的结果。

+0

对不起,但它不起作用。我更改了char number1中的int number1,但我仍然遇到同样的问题。 – Ordo 2010-10-23 20:04:38

+0

您还需要更改%d并将其设置为%c – rpoplai 2010-10-24 19:25:50