简体   繁体   English

如果将字符分配给C中的int变量会怎样?

[英]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.

相关问题 C/C++ 中未初始化的变量会怎样? - What happens to uninitialized variables in C/C++? 当分配给另一个变量时,C 中的结构中的 malloced 数据会发生什么情况? - What happens to malloced data in a struct in C when it is assigned to another variable? C,函数完成后的变量会发生什么? - C, what happens with the variables of a function when it finish? C将int *作为参数,参数类型为int **会发生什么? - C what happens putting int* as parameter where parameter type is int**? 当我在C中将long int分配给int时会发生什么? - What happens when I assign long int to int in C? 在C中,当我们将int转换为struct *时,内存中会发生什么? - In C, what happens in memory when we do cast int to struct*? 在 C 中将 int 列表转换为 char 列表时会发生什么? - What happens when a int list is cast as a char list in C? 如果将 int 传递给 C 中的字节参数会发生什么? - What happens if you pass an int to a byte parameter in C? 这里发生了什么:.h 文件 C 中的 typedef int (*ptr) (void) - what happens here: typedef int (*ptr) (void) in .h file C 在“ if”条件下将变量赋值为零时会发生什么? - What happens when a variable is assigned to zero in an `if` condition?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM