How to create a string-type variable in C

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

    Normally we use "&" in scanf but you shouldn't use it before variable "name" here. Because "name" is a char array. When the name of a char array is used without "[]", it means the address of the array.

    0 讨论(0)
  • 2021-02-04 08:56

    The int your putting is not a string, a string looks like "char myString[20]". Not like "int name", that's an integer and not a string or char. This is the code you want:

             int main(int argc, const char * argv[])
    {
    
    char name[9999];
    printf("What is your name?\n");
    scanf("%s", name);
    system("cls");
    printf("Your name is %s", name);
    
    return 0;
    }
    
    0 讨论(0)
  • 2021-02-04 08:59
    char name[60];
    scanf("%s", name);
    

    Edit: restricted input length to 59 characters (plus terminating 0):

    char name[60];
    scanf("%59s", name);
    
    0 讨论(0)
  • 2021-02-04 09:02

    It's easy!

    Just put this line below, atop of your main() function.

    typedef string char*;
    

    This allows you to create a string variable as you do with integers or characters in C. After that, your program should look like this:

    #include <stdio.h>
    
    typedef char* string;
    
    int main(void) {
        string a = "Hello";
        printf("%s\n", a);  // %s format specifier for String
        return 0;
    }
    

    For a live demonstration, visit this REPL.it.

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

    C does not have a string variable type. Strings can be stored as character arrays (char variable type). The most basic example I would add up to the rest is:

    int main()
    {
       char name[] = "Hello World!";
       printf("%s",name);
       return(0);
    }
    
    0 讨论(0)
  • 2021-02-04 09:06

    In C you can not direct declare a string variable like Java and other language. you'll have to use character array or pointer for declaring strings.

    char a[50];
    printf("Enter your string");
    gets(a);
    

    OR

    char *a;
    printf("Enter your string here");
    gets(a);
    

    OR

    char a[60];
    scanf("%59s",a);
    
    0 讨论(0)
提交回复
热议问题