I'm a beginner and just learning structures in C, but I encountered a small problem. This is the code:
struct Phone{
char name[50];
double screensize;
int memory;
int camera;
};
int main(){
struct Phone phone1;
printf("What model do you have? ");
fgets(phone1.name,50, stdin);
printf("How many MP does the camera have? ");
scanf(" %d", &phone1.camera);
printf("How much memory does you phone have? ");
scanf(" %d", &phone1.memory);
printf("You entered you have: \n");
printf("Model: %s \nCamera: %d \nMemory: %d", phone1.name, phone1.camera, phone1.memory);
}
It doesn't have any errors but, when I run it and input my stuff, the last printf from the code will display the model name, a line of white space, and then the camera and memory on consecutive rows. I want to get rid of that line of white space. I tried to leave a white space in scanf before all %d in order to discard that line, but it doesn't work (I've read that scanf reads the newline when you input something first and, to prevent that, we just need to add a space to flush the buffer first).
Here you input a line from console:
printf("What model do you have? ");
fgets(phone1.name,50, stdin);
it captures also a '\n' character, and then you print:
printf("Model: %s \nCamera: %d \nMemory: %d", phone1.name, phone1.camera, phone1.memory);
// ^ ^ there you print that '\n' in phone1.name and second hardcoded
Related
I might miss something really important but I cannot figure out and my teacher does not know either. I am reading char (y/n) as a console input answer, many times, (I do know about " %c" stuff.) I manage to read like 3-4 "y"-s but after that one fails, looks like a NULL and then manages the rest fine.
Functions:
scanf for reading console
fprintf for writing to file
Even though I tried many ways, every time one of my variables fails to contain the real character. When I printf the struct element one by one it fails the same one every time. When I try to read that very one variable of the struct it prints corruptly the y answer. I will include code too, I input as:
address : asdf (whatever really)
size: 0
rest of them are y except the very last. I used to press 2020.
Actual reading:
struct s_orders order;
printf("Address: ");
scanf(" %s", order.address);
printf("Size of fields(m^2): ");
scanf(" %d", &order.size);
printf("Paint ordered?(y/n): ");
scanf(" %c", &order.paint);
printf("Revert ordered?(y/n): ");
scanf(" %c", &order.revet);
printf("Water-gas ordered?(y/n): ");
scanf(" %c", &order.proba);
printf("Kitchen creation ordered?(y/n): ");
scanf(" %c", &order.uniq);
printf("Uphol ordered?(y/n): ");
scanf(" %c", &order.uphol);
printf("Expiration date: ");
scanf(" %s", order.date);
struct:
struct s_orders
{
/* data */
char address[100];
int size;
char paint;
char revet;
char proba;
char water;
char uniq;
char uphol;
char date[100];
};
Expected result:
"asdf;0;y;y;y;y;y;y;2020;"
Gotten:
"asdf;0;y;y;y;(random char here);y;y;2020;"
Edit:
- I am simply bad at focusing, I forgot to ask for input for water variable. Thanks for help!
I am working on my assignment and this is the issue that I bumped into. In the assignment, it says that the input value for the middle initals should be this - "L. A.". However, once I run my program it prints some printf functions on the same line, skipping the scanf function. I have went through a lot of topics about that " %c" issue, but I still can not make my program run properly. Some of the variables are from .h file. The actual assignment is bigger, however it is pretty much repetative so I thought if I figure out how to fix this certain issue I will be able to finally finish my assignment.
int main(void){
// Declare variables here:
char ch;
struct Name FullName = { {'\0'} };
struct Address AddressInfo = { 0, '\0', 0, '\0', '\0' };
struct Numbers PhoneInfo = { {'\0'} };
// Display the title
printf("Contact Management System\n");
printf("-------------------------\n");
// Contact Name Input:
printf("Please enter the contact’s first name: ");
scanf("%s", &FullName.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &ch);
if (ch == 'y') {
printf("Please enter the contact’s middle initial(s): ");
scanf(" %s", FullName.middleInitial);
}
printf("Please enter the contact’s last name: ");
scanf(" %s", &FullName.lastName);
// Contact Address Input:
printf("Please enter the contact’s street number: ");
scanf("%d", &AddressInfo.streetNumber);
OUTPUT (I have highlighted input values):
Contact Management System
-------------------------
Please enter the contactÆs first name: *Artem*
Do you want to enter a middle initial(s)? (y or n): *y*
Please enter the contactÆs middle initial(s): *L. A.*
Please enter the contactÆs last name: Please enter the contactÆs street number:
The %s format specifier reads a sequence of characters terminated by whitespace. When you enter L. A., only L. gets read into middleInitial because it stops reading at the space and A. is left in the input buffer. On the next scanf, it immediately reads those buffered characters so it doesn't stop to prompt for anything.
The simplest way to handle this is to leave out the space when inputting, i.e. L.A.. If you want to support whitespace, you'll want to get rid of scanf entirely and read everything a full line at a time using fgets. Note that fgets also reads in the trailing newline, so you'll need to strip that out.
I tried to do a small Worker Register, but it skips completely the second scanf, which gets address value. I am a beginner, so I do not know what I am doing wrong. Here is the code:
#include <stdio.h>
int main()
{
// var
char n[256], ad[256]; // n - Name, ad - Address
int i, ag; // i - Income, ag - Age
// code
printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
scanf("%255[^\n]", n);
printf("Address: ");
scanf("%255[^\n]", ad);
printf("Age: ");
scanf("%d", &ag);
printf("Income: R$");
scanf("%d", &i);
printf("Worker %s\nAddress: %s\nAge: %d\nIncome: R$%d", n, ad, ag, i);
return 0;
}
I really appreciate any help you can provide!
Nad's hack of adding a getchar() seems to fix it, but I wouldn't use scanf for reading strings if I were you.
It's nicer to use fgets() reading strings instead. scanf on a string is problematic. See: Reading a string with scanf
e.g.
#include <stdlib.h>
...
printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
fgets(n, 256, stdin);
...
Regarding the size parameter in fgets(). The man page states:
fgets() reads in at most one less than size characters from stream
and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte ('\0') is stored after the last character in
the buffer.
Therefore you enter the size of the buffer and ignore the null byte as fgets will do that work for you.
Just simply add a getchar(); To be honest, I don't know why but this has happened to me plenty of times in school. It seemed to fix it :)
code:
#include <stdio.h>
int main()
{
// var
char n[256], ad[256]; // n - Name, ad - Address
int i, ag; // i - Income, ag - Age
// code
printf("Welcome to the Worker Register\n\nWorker Data\n\nName: ");
scanf("%255[^\n]", n);
printf("Address: ");
getchar();
scanf("%255[^\n]", ad);
printf("Age: ");
scanf("%d", &ag);
printf("Income: R$");
scanf("%d", &i);
printf("Worker %s\nAddress: %s\nAge: %d\nIncome: R$%d", n, ad, ag, i);
return 0;
}
"%255[^\n]" meant input up to newline(accepts inputs other than newline).(The newline isn't included.)
So, there is a newline in the input buffer(of stdin),
second scanf (scanf("%255[^\n]", ad); ) also accepts inputs other than newline,
So, It will not be entered.
Therefore you need to consume the newline in first scanf.
E.g scanf("%255[^\n]%*c", n); %*c ignores one character(That is the newline).
Since %d of 3rd scanf skips the previous white-spaces, %*c isn't necessary for 2nd scanf.
I want to make a program which take Roll No and Full name as input and simply display it
My code is . this code skip scaning value of n through gets function. Why this error occur and how to over come this?
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30];
printf("enter your roll no");
scanf("%d",&r);
printf("enter your full name");
gets(n);
printf("roll no is %d ",r);
printf("name is %s ",n);
getch();
}
while the below code scan the first gets value and skips the second one.
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30], f[30];
printf("enter your roll no");
scanf("%d",&r);
printf("enter your full name");
gets(n);
printf("enter your full name of your father ");
gets(f);
printf("roll no is %d ",r);
printf("name is %s ",n);
printf("father name is %s ",f);
getch();
}
The code DOES NOT skip scanning the value of 'n'.
I believe that when you run the program, you enter the Roll No and then press the ENTER key on your keyboard.
This is the cause.
As soon as you press the ENTER key, the escape sequence '\n' is saved in the array n. Your gets() command is executing perfectly.
In the second case, the variable 'n' stores the escape sequence and the next variable 'f' takes the string you enter next.
To make your code work just enter your scanf statement like this:-
scanf("%d ",&r);
Notice the space after %d.
Try this code-
#include<stdio.h>
int main(void)
{
int r;
char n[30], f[30];
printf("Enter your roll no");
scanf("%d ",&r); // I have inserted a space after %d
printf("Enter your full name");
gets(n);
printf("Enter your full name of your father ");
gets(f);
printf("\nRoll no is %d ",r);
printf("\nName is %s ",n);
printf("\nFather name is %s ",f);
return 0;
}
TIP:- You must try not to use gets() and puts()
You can read more about it here.
The simple solution for the problem is to add fflush(stdin); between scanf(); and gets();
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
char n[30],fn[30];
clrscr();
printf("\nEnter roll ");
scanf("%d",&r);
fflush(stdin);
printf("\nEnter name ");
gets(n);
printf("\nEnter father name ");
gets(fn);
printf("\n\nRoll %d",r);
printf("\nname %s",n);
printf("\nfather name %s",fn);
getch();
}
Using scanf instead of gets will solve your problem:
scanf("%s", n); // Read in your name
Please note that when reading in any string like this you should use safe functions that are passed the length of the string (for example scanf_s from MSDN).
I don't know why it gets skipped but what you could do to avoid any other confusion like fflush(stdin) or fgets etc etc.
Just use gets(string) on the next line. So when it skips the first gets command it goes onto the other one.
Try that
Cheers,
;)
I just had the same problem two hours ago, but to solve this situation easily, all you have to fo is to add a "getchar()" after the "scanf()" and before the "gets()", so that the extra "\n" goes to the "getchar()" and you can type as you want in the next "gets()".
I was also facing the same problem as mentioned above.. so with the help of the answers mentioned here and using hit and trial method, I found that when we press enter after giving input to any variable using scanf(), \n is stored in the next gets() function.. and next time it doesn't take any input from the keyboard.. so to avoid this just use getchar() in between the scanf() nd gets() nd also remember that getchar() takes only 1 character.. so don't give any extra input to scanf() as again this will be stored and will be used in gets() nd the problem will remain the same....
hope this will help..
thank u..
This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
I'm trying to run the following code in the basic ubuntu gcc compiler for a basic C class.
#include<stdio.h>
struct emp
{
int emp_num, basic;
char name[20], department[20];
};
struct emp read()
{
struct emp dat;
printf("\n Enter Name : \n");
scanf("%s", dat.name);
printf("Enter Employee no.");
scanf("%d", &dat.emp_num);
//printf("Enter department:");
//fgets(dat->department,20,stdin);
printf("Enter basic :");
scanf("%d", &dat.basic);
return dat;
}
void print(struct emp dat)
{
printf("\n Name : %s", dat.name);
printf("\nEmployee no. : %d", dat.emp_num);
//printf("Department: %s", dat.department);
printf("\nBasic : %d\n", dat.basic);
}
int main()
{
struct emp list[10];
for (int i = 0; i < 3; i++)
{
printf("Enter Employee data\n %d :\n", i + 1);
list[i] = read();
}
printf("\n The data entered is as:\n");
for (int i = 0; i < 3; i++)
{
print(list[i]);
}
return 0;
}
I want the name to accept spaces.
The problem comes when I'm entering the values to the structures. I am able to enter the name the first time but the subsequent iterations don't even prompt me for an input.
I've tried using fgets, scanf("%[^\n]",dat.name) and even gets() (I was desperate) but am the facing the same problem every time.
The output for the 1st struct is fine but for the rest is either garbage, the person's last name or just blank.
Any ideas?
When reading a string using scanf("%s"), you're reading up to the first white space character. This way, your strings cannot include spaces. You can use fgetsinstead, which reads up to the first newline character.
Also, for flushing the input buffer, you may want to use e.g. scanf("%d\n") instead of just scanf("%d"). Otherwise, a subsequent fgets will take the newline character and not ask you for input.
I suggest that you experiment with a tiny program that reads first one integer number and then a string. You'll see what I mean and it will be much easier to debug. If you have trouble with that, I suggest that you post a new question.
The problem is that scanf("%[^\n",.. and fgets don't skip over any whitespace that may be left over from the previous line read. In particular, they won't skip the newline at the end of the last line, so if that newline is still in the input buffer (which it will be when the last line was read with scanf("%d",..), the scanf will fail without reading anything (leaving random garbage in the name array), while the fgets will just read the newline.
The easiest fix is to add an explicit space in the scanf to skip whitespace:
printf("\n Enter Name : \n");
scanf(" %19[^\n]", dat.name);
This will also skip over any whitespace at the beginning of the line (and blank lines), so may be a problem if you want to have a name that begins with a space.
Note I also added a length limit of 19 to avoid overflowing the name array -- if the user enters a longer name, the rest of it will be left on the input and be read as the employeee number. You might want to skip over the rest of the line:
scanf("%*[^\n]");
This will read any non-newline characters left on the input and throw them away. You can combine this with the prior scanf, giving you code that looks like:
printf("\n Enter Name : ");
scanf(" %19[^\n]%*[^\n]", dat.name);
printf("Enter Employee no. : ");
scanf("%d%*[^\n]", &dat.emp_num);
printf("Enter department : ");
scanf(" %19[^\n]%*[^\n]", dat.department);
printf("Enter basic : ");
scanf("%d%*[^\n]", &dat.basic);
This will ignore any spurious extra stuff that someone enters on a line, but will still have problems with someone entering letters where numbers are expected, or end-of-file conditions. To deal with those, you need to be checking the return value of scanf.
What you have tried was:-
scanf("%[^\n]",dat.name)
In this you forgot to specify the specifier.
You can try to use this:-
scanf ("%[^\n]%*c", dat.name);
or fgets() if you want to read with spaces.
Note:- "%s" will read the input until whitespace is reached.