Why, in C code, would a gets and puts behave differently when nothing is changed but the letters going into it?

StackOverflow https://stackoverflow.com/questions/21587590

  •  07-10-2022
  •  | 
  •  

Question

Hey guys (and girls), I have tried and tried to understand this. I have even stepped through with gdb and cannot understand it. So, I'm going to have to bother one of you guys. I have a simple menu where each choice is an integer, 1 through 12, monotonically increasing like normal. Well, I'm trying to code it so that if you select, say, five (5) it begins at there and continues to iterate through by asking name, age, ect. This is for an assignment so please don't tell me how to do that. All I need to know is for choice number 1 I am using an if statement and that if statement begins with these lines...

    printf("Enter Name: \n");
    gets(name);
    printf("Name: ");
    puts(name);
    printf("\n");

This code works exactly as intended. Then, later in the statement, after doing a few of the same type of thing, except using scanf for a float in the block just before. I have this code...

    printf("Enter Major: \n");
    gets(major);
    printf("Major: ");
    printf("\n");

This code will not wait on any input. It just prints out Major: then Major: again on the next line. I can't understand it. I stepped through with gdb and it worked properly when stepping. Then, when I run it the same thing happens again. Would someone please let me know what is going on? Thanks a lot, in advance, for the help. I know the vast majority of the people on here are professionals and don't care to be bugged with things so simple but I just cannot find the answer and my professor has left for the day. THanks guys. -court

Perhaps I should give you guys the code just before the problematic code. It is this, which works as intended... printf("Enter Height: \n"); scanf("%f", &height); printf("Height: %f2.1.", height); The variables involved are declared as... char name[25], major[25]; and float height. Thanks again.

Was it helpful?

Solution

except using scanf for a float in the block just before

is the key to your problem. If you do scanf("%f", &var), and enter a number terminated with a line feed, scanf will NOT read the line feed. Try entering "123abcd" for your float and you'll see the abcd will get stuffed into major.

Use scanf("%f ", &var) to skip over any potential whitespace behind your number (note the blank in the format string).

Besides, you shouldn't use gets, as it may cause buffer overflows, but if you're just starting to learn, this probably isn't your main problem right now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top