How to create a variable of type string in C

Question

How to declare a string variable in C?

Background

In my search, to learn the basics of c , I try to transfer one of my old , Bob , to C. In the program, the script asks the user for information about himself, and then spits out the answers. Almost all of these variables use raw_input for their information - the variables are strings. But I did not find a way to declare C variables.

code

So far, I have been trying to declare a variable of type char and int. Here is the code, switch the type at your leisure.

 int main(int argc, const char * argv[]) { int name; printf("What is your name?"); scanf("%s",&name); printf("Your name is %s", name ); return 0; } 

Error message

When I run this code, Xcode returns some strange things. This part of globidty-gloop is highlighted.

 0x7fff96d2b4f0: pcmpeqb(%rdi), %xmm0 

Lasty, this Yahoo answer said that I had to use something called character array . This was published 5 years ago, so I suggested that there is a better way.

EDIT

I follow the C Programming Guide.

+4
source share
5 answers
 char name[60]; scanf("%s", name); 

Edit: limited input length to 59 characters (plus completion 0):

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

int your put is not a string, the string looks like "char myString [20]". Not like an "int name", it's an integer, 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; } 
+2
source

XCODE TEST

You can do it:

 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 an array, it is useful to avoid errors

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

Instead of int used for int number (1, 2, 3, ecc.); Instead of a floating point number you need to use float

+1
source

In C, you cannot directly declare a string variable such as Java and another language. you will have to use an array of characters or a pointer to declare 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); 
+1
source

replace the name int; whose purpose. 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; } 
-1
source

Source: https://habr.com/ru/post/1469372/


All Articles