[英]What happens if characters are assigned into int variables in C
I am trying to get a integer value from argv[1]
. 我正在尝试从
argv[1]
获取一个整数值。
I want to know what happens if the user inputs a character so that I can avoid it. 我想知道如果用户输入一个字符会发生什么情况,那么我可以避免使用它。 I tried '\\0' and currently this doesn't work.
我尝试了“ \\ 0”,目前无法正常工作。
int main(int argc, char* argv[]){
int MAX_SIZE;
MAX_SIZE=atoi(argv[1]);
while(MAX_SIZE=='\0'){
printf("plz input in correct format: ");
scanf("%d", &MAX_SIZE);}
Any help would be appreciated. 任何帮助,将不胜感激。
Your code is a bit weird but from what I understand you want to check if a character is a number or not, for that you can use the function isdigit()
to check if the entered value is a number or not, something like this: 您的代码有点奇怪,但是据我了解,您想检查字符是否为数字,为此,您可以使用
isdigit()
函数检查输入的值是否为数字,如下所示:
char c='a';
if(isdigit(c)) //if true, i.e. it returns non-zero value
cout<<"number";
else // if false, i.e. it returns zero
cout<<"Char";
I have written C++ code as I am more comfortable in C++ but the function isdigit()
works in both C and C++. 我已经编写了C ++代码,因为我对C ++更加满意,但是
isdigit()
函数在C和C ++中均可使用。
# include <stdio.h>
# include <stdlib.h>
int main ( int argc, char *argv[] )
{
int i, n, a;
printf("\n argv[0] = %s\n", argv[0] );
if ( argc <= 1 )
{
printf("\n");
printf(" argc = %d, no arguments given on command line\n", argc );
printf("\n");
}
for ( i = 1; i < argc; i++ )
{
n = sscanf( argv[i], "%d", &a );
if ( n == 1 )
{
printf(" read %d off command line in argv[%d]\n", a, i );
}
else
{
printf(" sscanf failed, n = %d, argv[%d] = %s\n", n, i, argv[i] );
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.