Reputation: 77
I am new to C language and working on a small program.
Actually I am trying to take string from the user using scanf. But whenever I enter string with space, program keeps on running infinite and I had to press stop button. I have seen examples online and I have used them as well but that give me a new error then.
Here is my code
struct student s1;
char input[MAX_NAME_SIZE];
printf("Enter name>");
scanf("%s",input);
if(strlen(input) > 10)
{
int l;
for(l = 0 ;l < 10;l++)
s1.name[l] = input[l];
}
int error = 0;
do
{
if(error == 1)
printf("Invalid day. ");
printf("Enter birthday: day>");
scanf("%u",&s1.birthday.day);
error = 1;
}while(s1.birthday.day < 1 || s1.birthday.day > 31); //checking the criteria
I also have used scanf("%[^\n]s,input) but it then skip the scanf and go to the second scanf.
Please help
Upvotes: 0
Views: 1150
Reputation: 41
instead of using
scanf("%s",input);
you can use
gets(input);
It is a function of cstring
header file and works same.
You may get the problem because scanf
accepts only space delimited strings. gets
accepts a complete single line, so it may solve your problem.
Hopefully this will work!
EDIT1: Just got it from one of the comments.
use fgets()
instead. because gets()
doesn't provide buffer overflow protection.
Upvotes: 2
Reputation: 5079
I would never recommend you to use scanf for input which is more than one word. getline() would be the best choice for entering the whole line (etc. Mike Myers 13/04/85) and it's pretty much safe. You also get null terminated string.
You can use this function for example:
char *input(char *output)
{
char *Buffer = NULL;
size_t size = 0;
int count = 0;
printf("%s", output);
count = getline(&Buffer, &size, stdin);
Buffer[count-1] = '\0';
return Buffer;
}
In your case it would be best to use it like this:
s1->name=input("Enter the name");
s1->birthday=input("Enter the birthday");
Or you can enter the whole line and use strtok() to parse it.
Upvotes: 0
Reputation: 409176
The problem, as I hinted about in my first comment, is that scanf
only reads space delimited "words".
That means when you give a string with space in it as input, then scanf
will read the first part up to the space, and leave the rest of the input in the buffer. Then when you do your input in the loop, scanf
will see that it's not a number, and fail to extract the input from the buffer, leaving the input intact, so the next iteration of the loop scanf
will attempt to read and parse the exact same input as the last iteration, leading to an infinite loop.
There are also other problems with your code, like you not actually checking if scanf
failed or not (follow the link to a scanf
(and family) reference and read about what it returns), and not breaking out of the loop if error
is set.
Upvotes: 0