How to create a string-type variable in C

后端 未结 8 1390
没有蜡笔的小新
没有蜡笔的小新 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

提交回复
热议问题