How to create a string-type variable in C

扶醉桌前 提交于 2019-12-03 00:24:04
char name[60];
scanf("%s", name);

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

char name[60];
scanf("%59s", name);

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);

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;
}

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

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.

nemer tamimi

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!