script is supposed to take input from the user and display that input when info is entered. it is storing the information, but after regardless of input it does not display the information. I think it has something to do with the if statement not being setup correctly and the == "info" not being correct but can’t figure out how to do this.
#include <stdio.h>
int main()
{
char name;
int age;
printf("your name\n");
scanf("%s", &name);
printf("your age\n");
scanf("%s", &age);
char input;
scanf("%s", &input);
if(&input == "info")
{
printf("%s\n", &name);
printf("%s\n", &age);
}
}
>Solution :
The program has undefined behavior and could do just about anything.
-
nameis but onecharand can only fit one letter. It needs to fit at least two letters to be able to have the required null terminator\0(which is what tellsprintfetc where the string ends). Since it doesn’t,scanfwill write out of bounds. -
You use the wrong conversion specifiers for both
scanfandprintf.%sis for words/strings, notint.%dis the correct conversion specifier forint. -
if(&input == "info")compares two addresses not two strings. You should usestrcmpto compare strings. -
scanfs%sreads a word and if the name contains more than two words, you’re out of luck. I suggest usingfgetsto read strings instead of a word.
Slightly modified to not use scanf directly since it complicates things when mixing scanf and fgets:
#include <stdio.h>
#include <string.h>
int main() {
char name[256]; // room for 255 char + \0
int age;
char input[32];
puts("your name");
if (fgets(name, sizeof name, stdin) == NULL) return 1;
name[strcspn(name, "\n\r")] = '\0'; // chop off at \n or \r
puts("your age");
char tmp[16];
if (fgets(tmp, sizeof tmp, stdin) == NULL) return 1;
// now use sscanf on the tmp buffer and check that it succeeds:
if (sscanf(tmp, "%d", &age) != 1) return 1;
if (fgets(input, sizeof input, stdin) == NULL) return 1;
input[strcspn(input, "\r\n")] = '\0';
// compare the content of input with the string "input",
// 0 means that they are equal:
if (strcmp(input, "input") == 0) {
printf("%s\n", name);
printf("%d\n", age);
}
}