Using scanf for structure input [duplicate] - c

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 5 years ago.
The code attached with this post is part of a bigger program but I am experiencing problems while taking in input for my structured variable 'title' and 'author'.
The program seems to loop over it and move on to the next line. Also, while using [^\n] before 's' in the string specifier, it does the same however I read it is used to take a string as input using scanf. Read a few posts but can't figure out the issue.
Just starting with C, any help would be appreciated!
struct books{
char title[30];
char author[30];
char subject[20];
int quantity;
int book_id;
char *category;
int count;
float price;
};
struct books book;
book.book_id=id;
printf("\n\n\t\tBook Name:\n\t\t");
scanf(" %s",book.title);
printf("\n\n\t\tAuthor:\n\t\t");
scanf(" %[^\n]s",book.author);
printf("\n\n\t\tQuantity:\n\t\t");
scanf("%d",&book.quantity);
printf("\n\n\t\tPrice:\n\t\t");
scanf("%f",&book.price);

Use [^\n] before 's' in the string specifier in both the input "book.title" and "book.author".
I executed your code with those modifications. The code is correct.
You have been taking a space seperated String as the Title of Book.(like "Mein Kampf" as the Title.)
But you must understand that you cannot input space seperated words as a single String using Scanf. So the program loops over it and moves to the next line.
To take such inputs you will have to use gets or fgets function or use [^\n] before 's' in the string specifier.

Related

Understanding how C scanf input works [duplicate]

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 2 months ago.
I have a sample weird code like this:
#include<stdio.h>
int main(){
int t;
scanf("%d", &t);
while(t--){
char s[1];
scanf("%s", s);
}
}
I have test that if I have t from input that > 1 ( like t = 3) then put a single character to s, then the program ends, while t hasn't downed to 0 yet. Could anyone explain for me what happens here. Thanks for your help!
Change char s[1]; to char s[100]; or other length to allow at least as many characters as you will enter plus one for the terminating null character.
When scanf processes a %s, it appends a terminating null character to the end of the characters it matches to the %s. Since you declared s as char s[1];, there is no reserved room for the terminating null character, and scanf attempts to write beyond the reserved space.
Then the behavior of your program is not defined by the C standard.

Do while is not taking inputs in the order defines it only works for 1 scanf [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
My program should accept 2 int value as the number and the position at which it should be added. After that it should ask wheather you want to insert more Y/N? But my program dosen't take the input of char instead takes a garbage value and keeps on asking for numbers only.
I have tried using seperate scanf for each input.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,n;
char opt;
clrscr();
do{
printf("\nEnter the no. to be added and the position:");
scanf("%d%d",&x,&n);
printf("Do you want to insert more elements Y/N?");
scanf("%c",&opt);
printf("opt=%c x=%d n=%d",opt,x,n);
}while(opt!='N'&&opt!='n');
}
My o/p should be the value of each variables instead I get a garbage value in opt and the loop continues as it isn't 'n'.
The new line character is being read into your variables.
Change this line:
scanf("%c",&opt);
To this:
scanf(" %c",&opt);
The space consumes the new line character. This is only necessary for your " %c" format specifier. The "%d" does not require the space.

C - How to read a string with only spaces using scanf [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
I'm with a little problem while doing an excercise to learn C.
The problem is: I need to read a string from the user, but if he types just a space, I need to print a space. That's okay in theory.
But, when I type the space while the program is running, it doesn't understand it as a string and it keeps waiting for me to type other things.
I'm using the scanf("%[^\n]", string_name_here);
I appreciate your help, and have a nice day! o/
And sorry for my bad english, I hope you can understand this :)
Using char *fgets(char *str, int n, FILE *stream) will make your day.
According to man :
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.
Example program
#include <stdio.h>
#define MAXSTR 21
int main(void)
{
char my_str[MAXSTR] = {'\0'};
fgets(my_str, MAXSTR, stdin);
return 0;
}
Input :
Claudio Cortese
Output :
Claudio Cortese

Get words which contains space in c [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
I need to get words from user which contains space as I expressed at title with struct statement.
For example :
#include <stdio.h>
struct knowledge
{
char name[30];
}person;
int main()
{
scanf("%s",person.name);
printf("\n\n%s",person.name);
}
When I run this program and enter a sentence like "sentence" there is no problem. It show me again "sentence".
However, when I enter "sentence aaa" it shows me just first word ("sentence"). What is the matter here? Why it doesn't show me all ("sentence aaa") I entered?
Instead of scanf() use
fgets(person.name,sizeof(person.name),stdin);
It is always a bad idea to use scanf() to read strings. The best option is to use fgets() using which you avoid buffer overflows.
PS: fgets() comes with a newline character
%s format specifier stops scanning on encountering either whitespace or end of stream. hence, you cannot input a "sentence" with space using scanf() and %s.
To scan a "whole line" with space, you need to use fgets(), instead.

loop executes more than needed [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Store data in array from input [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code:
#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
println("Welcome to Number Guesser v 0.1 ");
println("Think of a number between 0 and 100 (and please, make it an integer!)");
println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
int guessed=0;
float curnum=100.0;
char cursign='?';
while(cursign!='y'){
if(cursign=='?' || cursign=='s'){
curnum=curnum/2;
}
else if(cursign=='b'){
curnum=curnum+curnum/2;
}
else{
printf("You are wrong. Stop it. %c . TEESST",cursign);
}
char askstring[4096];
sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
println(askstring);
scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
}
}
(I pasted all of it, since I am a c noob)
If the code looks like this, the loop will execute twice per user input, once with cursign= to whatever the user entered, and once with it equal to \n.
If I change the scanf line to
scanf("%c\n",&cursign);
It asks for the first input twice, then works as a charm. What's the problem, and what should I do?
Change this scanf("%c\n",&cursign); to this scanf(" %c",&cursign);. This will eat up the trailing newline character.
Also as per standard main should return an int (even though this is not the reason for your problem). According to C standards main should be int main(void) or int main(int argc, char* argv[])
When you enter a character like y and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) gets placed in the input buffer. The first character gets consumed by the scanf but the newline remains in the input buffer so what happens is that the next time you enter something there 3 characters newlinechar + 'y' + newlinechar. So that makes scanf behave funny.
This is a great link from Grijesh - C Printf and Scanf Reference

Resources