Program bypass first fgets - c

The problem is when it asks the user to enter the name of the band.The program bypass the first fgets, but executes the printf and not the fgets. I tried to handle this problem with if but again the same problem. Bypass the first fgets. I provide you an image also.
#include <stdio.h>
#include <stdlib.h>
struct cd
{
char band[100];
};
struct cd *music;
int main()
{
int n,i;
printf("Give how many albums you want: ");
scanf("%d",&n);
struct cd *music = malloc(sizeof(struct cd)*n);
for(i=0;i<n;i++)
{
printf("\nEnter Band: ");
fgets(music->band,sizeof(music->band),stdin);
music++;
}
for(i=n-1;i>=0;i--)
music--;
for(i=0;i<n;i++)
{
printf("\nBand: %s",music->band);
music++;
}
printf("\n\n");
return 0;
}

Scanf() treats '\n' as a character and since it is not in the format string, it leaves it there.
try this
char newline;
int n,i;
printf("Give how many albums you want: ");
scanf("%d%c",&n,&newline);
This will remove the '\n' from the stdin.

when you read with scanf() it reads everything leaving the following '\n' from the end
And Now when you try to read with fgets()it reads the'\n' character left by scanf
To solve this you can use fgetc(stdin); after your scanf so that it gets consume.

Related

Struct and a symbol array

can you help me?
i have a problem with char* station;
when i fill my gaps, everithing is alright, but when i am with printf("%d)Input its stations: ",i+1);. It's a problem, i mean: i enter chech-joch-chor-dsh-dsh but i need to enter chech joch chor dsh dsh(these are names of stations,it's an example).So it prints ONLY THE FIRST WORD, i dont why.. check this out please... (i understand that i need to free what i'have taken). Please, explain why it is so, why the first?.. give me a hint..
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct info_bus_{
int number;
int begin;
int end;
char* stations;
int time_working;
}info_bus;
int main()
{
info_bus *b=NULL;
int i,n;
char buffer[128];
printf("How many buses u have: ");
scanf("%d",&n);
b=(info_bus *)malloc(n*sizeof(info_bus));
for(i=0;i<n;i++){
printf("Input the number of a bus: ");
scanf("%d",&(b+i)->number);
printf("%d)Input when it starts to work: ",i+1);
scanf("%d",&(b+i)->begin);
printf("%d)Input when it finishes to work: ",i+1);
scanf("%d",&(b+i)->end);
printf("%d)Input its stations: ",i+1);
scanf("%127s", buffer);
b[i].stations = (char*) malloc(strlen(buffer) + 1);
strcpy(b[i].stations, buffer);
printf("Input time working: ");
scanf("%d",&(b+i)->time_working);
}
for (i=0;i<n;i++){
printf("\n[%d].the number of a bus: %d",i+1,b->number);
printf("\n[%d]. Begin at: %d",i+1,b->begin);
printf("\n[%d]. Finishes at: %d",i+1,b->end);
printf("\n[%d]. Stations: %s",i+1,b->stations);
printf("\n[%d]. Time working: %d",i+1,b->time_working);
printf("\n");
}
return 0;
}
but when i use gets()
it is:
scanf("%127s", buffer);
stops reading after encountering a newline. If you want to be able to read multiple words then use fgets():
fgets(buffer, sizeof buffer, stdin);
Note: fgets() will also read the newline character if there's room. You can remove it if necessary:
buffer[strcspn(buffer, "\n")] = 0; /* to remove the newline */
Generally, avoid using scanf() even for other inputs. It's error prone. See: Why does everyone say not to use scanf? What should I use instead?
Also, the cast of malloc() is unncessary. See: What's wrong with casting malloc's return value?

Loop gets terminated without any error

well I have been trying to write this program which accepts any number of integers until the condition is true using do while loop but the loop gets terminated even if the condition is met.I am not able to understand the flaw in my code... I would be thankful for any help
#include<stdio.h>
#include<conio.h>
int main()
{
int max,min,test;
char next;
printf("enter an integer:\n");
scanf("%d",&max);
min=max;
do
{
printf("enter next integer:\n");
scanf("%d",&test);
if(test>max)
max=test;
else if(test<min)
min=test;
printf("want to enter next number y/n\n");
scanf("%c",&next);
}while(next=='y');
printf("Maximum=%d\nMinimum=%d\nRange=%d\n",max,min,max-min);
getch();
}
Try this ...
#include<stdio.h>
#include<conio.h>
int main()
{
int max,min,test;
char next;
printf("enter an integer:\n");
scanf("%d",&max);
min=max;
do
{
printf("enter next integer:\n");
scanf("%d",&test);
getchar(); // added this
if(test>max)
max=test;
else if(test<min)
min=test;
printf("want to enter next number y/n\n");
scanf("%c",&next);
}while(next=='y');
printf("Maximum=%d\nMinimum=%d\nRange=%d\n",max,min,max-min);
getch();
}
After taking input test when you are pressing Enter your code takes Enter as a new line character. To avoid this, take that new line character through getchar().
When reading input through scanf(), It will not consume return key so '\n' will remain there in stdin waiting to read for next char input. That is why your program is coming out of loop. So to avoid this problem use getchar() after scanf("%d",&test);.
in else if (condition) you have written test<min, where variable min does not have any value. you should write
else if(test<max)
(
min = test
)

Getting specific # of characters

I want to get only 2 characters in my program. I tried fgets but I can get it to work. How do you suggest that I implement this? Or is there any alternative?
char code[2];
printf("Enter code: \n");
scanf("%s", code);`
I want to limit the number of characters that can be entered to two.
To read two characters and ignore white space you can do:
#include <stdio.h>
int main() {
char code[2];
printf("Enter code:\n");
if (scanf(" %c %c", &code[0], &code[1]) == 2) {
printf("successfully read '%c' and '%c'\n", code[0], code[1]);
}
return 0;
}
to not ignore white space use "%c%c" as the format.
Try this code
#include<stdio.h>
#include<conio.h>
void main()
{
char code;
clrscr();
printf("enter the code\n");
scanf("%2s",code);
printf("%s",code);
getch();
}

Fgets skipping inputs [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 8 years ago.
I've tried looking around and I can't seem to find where the error lies. I know it must have something to do with the way I used fgets but I can't figure out for the life of me what it is. I've read that mixing fgets and scanf can produce errors so I've even changed my second scanf to fgets and it still skips the rest of my inputs and only prints the first.
int addstudents = 1;
char name[20];
char morestudents[4];
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf("%s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
}
My inputs are Joe, yes, Bill, yes, John, no. All goes according to plan if I utilize scanf in lieu of the first fgets but I would like be able to use full names with spaces included. Where am I going wrong?
When the program displays Do you have more students to input? and you input yes and then hit enter on console, then \n will be stored in input stream.
You need to remove the \n from the input stream. To do that simply call getchar() function.
It will be good if you don't mix scanf and fgets. scanf has lots of problems, better use fgets.
Why does everyone say not to use scanf? What should I use instead?
Try this example:
#include <stdio.h>
#include <string.h>
int main (void)
{
int addstudents = 1;
char name[20];
char morestudents[4];
int students, c;
char *p;
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
//Remove `\n` from the name.
if ((p=strchr(name, '\n')) != NULL)
*p = '\0';
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf(" %s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
//Remove the \n from input stream
while ( (c = getchar()) != '\n' && c != EOF );
}
return 0;
}//end main

Why doesn't scanf() take inputs from the user while dealing with strings?

My code is as follows
typedef struct
{
char name[15];
char country[10];
}place_t;
int main()
{
int d;
char c;
place_t place;
printf("\nEnter the place name : ");
scanf("%s",place.name);
printf("\nEnter the coutry name : ");
scanf("%s",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%c",&c);
printf("You entered %c",c);
return 0;
}
If I run the program, it prompts for place name and country name, but never waits for the character input from user.
I tried
fflush(stdin);
fflush(stdout);
Neither work.
Note : Instead of a character, if I write a similar code to get an integer or a float, it prompts for values and the code works just fine.
int d;
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%d",&d);
Why does this happen? Is there anything wrong in the code?
The problem is that scanf leaves the whitespace following entered non-whitespace characters in the stream buffer, which is what the scanf(%c...) then reads. But wait a second...
In addition to being tricky to get right, such code using scanf is horribly unsafe. You're much better off using fgets and parsing the string later:
char buf[256];
fgets(buf, sizeof buf, stdin);
// .. now parse buf
fgets always gets a full line from the input, including the newline (assuming the buffer is large enough) and you thus avoid the problem you're having with scanf.
You can use string instead of character for scanf.
printf("\nEnter the place name : ");
scanf("%s%*c",place.name);
printf("\nEnter the coutry name : ");
scanf("%s%*c",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%c",&c);
printf("You entered %c",c);
Try adding spaces before the % sign in scanf().
I have provided the modified code below.
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[15];
char country[10];
} place_t;
int main()
{
int d;
char c;
place_t place;
printf("\nEnter the place name : ");
scanf(" %s",place.name);
printf("\nEnter the coutry name : ");
scanf(" %s",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf(" %c",&c);
printf("You entered %c",c);
return 0;
}

Resources