How to create a string-type variable in C

后端 未结 8 1371
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 08:42

Question

How to declare a string variable in C?

Background

In my quest to learn the basics of c, I am trying to port on

相关标签:
8条回答
  • 2021-02-04 09:06

    TESTED ON XCODE

    You can do so:

    int main(int argc, const char * argv[])
    {
    
        int i;
        char name[60]; //array, every cell contains a character
    
        //But here initialize your array
    
        printf("What is your name?\n");
        fgets(name, sizeof(name), stdin);
        printf("Your name is %s", name );
    
        return 0;
    }
    

    Initialize the array, is good to avoid bug

    for(i=0;i<60;i++){
          name[i]='\0'; //null
    }
    

    Instead int is used for int number (1, 2, 3, ecc.); For floating point number instead you have to use float

    0 讨论(0)
  • 2021-02-04 09:11

    replace int name; to--. char name[60];

    #include <stdio.h>
    int main()
    {
      char name[648];
      printf("What is your name?");
    
      scanf("%s", name);
      printf("Your name is %s", name );
    
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题