Reputation: 803
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
Upvotes: 1
Views: 333
Reputation: 4040
This is because when you write scanf('%s')
, on input test 1
the %s
only scans up to the first space and the input your program receives is actually only test
.
A useful thing to do in terms of debugging would be to do a
printf("Error: %s", input)
So you can see what scanf
is getting you.
If you just want whole lines of input, fgets()
is better to use.
Upvotes: 2
Reputation: 75389
The simple answer is to change "%s"
in scanf
to "%[^\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.
Upvotes: 3