I’m trying to create a simple program in C. Here is kinda what I have so far for the basics
#include <stdio.h>
int main()
{
char input[256];
while(1)
{
printf("Input: ");
scanf("%s", input);
if(strcmp(input, "help") == 0)
printf("HELP STUFF HERE\n");
else if(strcmp(input, "1") == 0)
printf("2\n");
else if(strcmp(input, "test 1") == 0)
printf("Test 1\n");
else if(strcmp(input, "test 2") == 0)
printf("Test 2\n");
else
printf("Error");
}
return 0;
}
I’m having some problems though. First of all I can’t use spaces. If I try test 1, I get the output of Error. Second problem I’m having is when it outputs Error, it prints it onto the user input prompt
The simple answer is to change
"%s"inscanfto"%[^\n]", which reads all characters other than a newline.The better answer is to change it to
"%255[^\n]", which does the same but includes bounds checking.The best answer is to use
fgets, which doesn’t have funky issues with what exactly it will read, or make it difficult to do proper bounds checking.