i tried to make a code for a friend in C but i have no idea why it's not working, could someone please help me? (i want a simple version-fix if it's possible, because i've only started to study c a couple of weeks ago)
#include <stdio.h>
#include<string.h>
int main ()
{
char *name="alina";
char *input;
printf ("what's your name? \n");
scanf ("%s",&input);
if (input=="alina")
printf("your name is %s good job!\n ",&name);
if (input!="alina")
printf("are you sure? open the program again and insert the correct name");
while (1);
You did some errors. First, if you want to insert a string, you can use the %s
, but you have to use an array of char
in which you can store that string. That's, you have to write something like this.
char input[100];
scanf("%s", input);
and then it'll work. This snippet of code means: I need to insert (store) a string. So first I create a place in which I can store it (pay attention that the string must be maximum of 99 characters; my array has size 100, but the last character is used to represent the end of the string), and then I use the scanf
to write what I want.
The second error is that if you want to compare two strings, you can't simply use the ==
or !=
, like when you do with numbers. The string.h
library lets you use the strcmp
function, like this:
if (strcmp(name, input) == 0) // this means the strings are equal
...
else
...
remembering that
char* name = "Alina";
char input[100];
Eventually, here you're an inspected version of your code:
#include <stdio.h>
#include <string.h>
int main() {
char* name = "Alina";
char input[100];
printf("What's your name?\n");
scanf("%s", input);
if (strcmp(name, input) == 0)
printf("Your name is %s good job!\n", name);
else
printf("Are you sure? Open the program again and insert the correct name\n");
return 0;
}
The while(1)
at the end of your code is absolutely dangerous, because it starts an infinite loop that never ends, crashing your program. You want to definitely remove it!