Question
How to declare a string variable in C?
Background
In my quest to learn the basics of c, I am trying to port one of my oldest python programs, Bob
, to C. In the program, the script asks the user for information on him or herself, and then spits out responses. Almost all of these variables use raw_input
for their information - the variables are strings. But, I have found no way to declare C variables.
Code
So far, I have tried to declare the variable as 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 weird stuff. This part of the globidty-gloop is highlighted.
0x7fff96d2b4f0: pcmpeqb(%rdi), %xmm0
Lasty, this Yahoo Answer said that I had to use something called a character array
. It was posted 5 years ago, so I assumed that there was a better way.
EDIT
I am following the tutorial at C Programming.
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.
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;
}