Get words which contains space in c [duplicate] - c

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.

Related

Trailing newline when using scanf() to take string input with whitespace [duplicate]

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Closed 28 days ago.
I am getting problem when using scanf() to take int input, then move to take a whole string that also accept whitespace in it. But somehow the scanf() take place first before the printf() even showed up. Still playing around with either scanf() and fgets() for proper solutions
Here is my snippet code
int age; char name_user[35];
printf("age\t: "); scanf("%d\n",&age);
printf("name\t: "); scanf("%[^\n]%*s", name_user);
printf("result\t: %s is %d years old\n",name_user,age);
with the output like this
age : 30
hotpotcookie
name : loremipsum
result : hotpotcookie is 30 years old
are there any workarounds for the input hotpotcookie take place in the name output? so it could be similar like this
age : 30
name : hotpotcookie
result : hotpotcookie is 30 years old
"\n" consumes 0 or more white-spaces until a non-white-space is detected. This means scanf() will not return at the end-of-line as it is looking for white-spaces after a '\n'.
scanf("%d\n",&age); does not return until detecting non-white-space after the numeric input.
Use scanf("%d",&age);.
scanf("%[^\n]%*s", name_user); also risks buffer overflow.
Use a width as in scanf(" %34[^\n]", name_user);
Better code checks the return value from scanf() before using the object(s) hopefully populated by the scan.
Even better code does not use scanf(). Instead use fgets() to read a line of user input into a string and then parse with strotl(), sscanf(), etc.

question about reading an input using fgets and scanf in c [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 3 years ago.
I have recently been trying to do an exercise in c.
I want to read the input which is something like: "SET 0" (note that the actual text will be parsed later).
I tried fgets as it is like that:
char in[20];
//ok, this reads the first line, the first input is meant to be a number
scanf("%s",in);
if(isdigit(in[0])){
char array[]={'?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?'};
auto counter = atoi(in);
while(counter !=0){
fgets(in, sizeof(in),stdin);
For some reason, when i type eg "SET 0" and i am using fgets the in variable is empty(will print nothing).
I tried scanf but it will not read the number.
Any ideas/suggestions of what i can do?
Thanks in advance!
Do not mix fgets() with scanf() until you know why scanf()` is evil.
fgets() read the left over '\n' of the first line of user input which scanf() did not read.

Strcmp() in "series" [duplicate]

This question already has answers here:
How to do scanf for single char in C [duplicate]
(11 answers)
compare a character on a char array by using strcmp
(2 answers)
Closed 5 years ago.
I want to compare some strings, but unfortunately I don't find any proper way to do it.
The idea behind is to ask for a keyboard input, read a variable, one symbol and if it is "y" or "n" ("yes" or "no" apparently) it executes certain activities. If the value of the char is neither of them, the question is asked again, until either of "y" or "n" is not pressed. I don't understand how to implement that.
#include <stdio.h>
#include <string.h>
int main()
{
char answer;
answer='a';
while (answer!='n'&&answer!='y')
{
printf("\nQuestion? (y/n) ");
scanf("%c",&answer);
}
return 0;
}
This actually works pretty nice, but if I don't press 'y' or 'n', the "while" starts again and due to a reason I cannot understand, the "printf" is executed one times more, than the length of the input. So if we run this code and we apply "asdf" as an input (four symbols) the "printf" in the "while" is displayed five (four plus one) times. The result is:
Question? (y/n)
Question? (y/n)
Question? (y/n)
Question? (y/n)
Question? (y/n)
Everything else works really nice in my code, but this... Obviously, this is not the best way to approach. I have also tried "strcmp()":
#include <stdio.h>
#include <string.h>
int main()
{
char answer='a';
while (strcmp(answer,'n')!=0&&strcmp(answer,'y')!=0)
{
printf("Question?");
scanf("%c",&answer);
}
return 0;
}
I don't know why, but the program doesn't even start. It is clear, that I haven't implemented "strcmp" properly and I don't understand what is wrong.
Any ideas, what should I do, so I can avoid multiple execution of the "printf" in the "while" or to make "strcmp" work the way I demand it to?
You probably want to read an entire line instead and interpret it as a whole. This way, you don't get the extra unwanted iterations when you enter a line with multiple characters, nor the extra one for the newline character. Look at the fgets() function.
scanf() is generally a poor choice beyond very simple input requirements, precisely because it is somewhat fuzzy and don't allow you to validate parts of the input before parsing it.
The %c format specifier to scanf will read any character, including whitespace characters such as a newline.
So if you enter in a letter and press the ENTER key, the scanf will read the letter and return, leaving the newline in the input buffer. On the next iteration of the loop, the scanf will immediately consume the newline left in the buffer and answer will contain the newline character. That's why you're seeing the prompt printed twice.
You need to add a leading space in your scanf format:
scanf(" %c",&answer);
The space will consume any whitespace characters that are entered so that answer will only contain non-whitespace.
The reason you're having problems with strcmp is because you're not actually comparing strings but individual characters. Each argument to strcmp is expected to be a pointer to a character array containing a string. Instead, you're passing in a single character. The value of that character is then interpreted as an address and dereferenced. This invokes undefined behavior.
In C, a string literal is represented this way: "n", but you have char literals, 'n' ... they're very different. Use a string literal for the argument, and it should work better.

Using scanf for structure input [duplicate]

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.

C scanf with spaces problem [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you allow spaces to be entered using scanf?
printf("please key in book title\n");
scanf("%s",bookname);
i inside the data like this :-
C Programming
but why output the data like this :-
C
lose the Programming (strings) ?
why
thanks.
The %s conversion specifier causes scanf to stop at the first whitespace character. If you need to be able to read whitespace characters, you will either need to use the %[ conversion specifier, such as
scanf("%[^\n]", bookname);
which will read everything up to the next newline character and store it to bookname, although to be safe you should specify the maximum length of bookname in the conversion specifier; e.g. if bookname has room for 30 characters counting the null terminator, you should write
scanf("%29[^\n]", bookname);
Otherwise, you could use fgets():
fgets(bookname, sizeof bookname, stdin);
I prefer the fgets() solution, personally.
Use fgets() instead of scanf()
Well bookname surly is some kind of char ;-)
Point is that scanf in this form stop on the first whitespace character.
You can use a different format string, but in this case, one probably should prefer using fgets.
scanf really should be used for "formatted" input.

Resources