#include<Stdio.h>
#include<conio.h>
void main()
{
char a[100];
clrscr();
printf("enter a paragraph\n");
scanf("%s",a);
printf("%s",a);
getch();
}
output:
enter a paragraph
my name is vasanth
my
how do I read the entire line "my name is vasanth" using scanf function?
Using the scanf function:
scanf("%99[^\n]", a);
Where %[^\n] is a character set specifier that allows all characters except newlines, and %99[^\n] limits the match to at most 99 characters (since a has space for that many characters plus the null terminator).
Alternatively, you can use
fgets(a, 100, stdin);
This is arguably more common, but be aware that it leaves the newline at the end intact.
This question has been asked multiple times and the answer to this is
Use
fgets(a,sizeof(a),stdin);
size_t n = strlen(a);
if(n>0 && a[n-1] == '\n')
a[n-1] = '\0';
If you want to use scanf() only then you need to do
scanf("%99[^\n]",a);
Where [^\n] tells read until newline character is encountered and 99 makes sure that there is not buffer overflow. Still fgets() is a good option to read strings compared to scanf()
You can use fgets as below
fgets (a, 100, stdin);
You can use fgets( ) function to read a line of text.
fgets(str , 100 , stdin);
You can also use gets( ) function if your string is small since this funtion has no buffer overflow protection.
gets(str)
U can also use scanf to do this as others have mentioned.
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
I have two questions:
why only when i do space in "%d " --> scanf("%d ", &num); it works?
I tried fflush(stdin) \ _flushall() between the scnaf and the gets and it doesn't works, it skips the gets.
When I do the space, it first does scanf then the gets and after that it print the number and print the string.
void main()
{
char ch, str[10];
int num;
printf("Enter your number : ");
scanf("%d ", &num);
printf("%d\n",num);
gets(str);
puts(str);
system("pause");
}
why only when i do space in "%d " --> scanf("%d ", &num); it works?
scanf("%d", &num); without a space after the "%d", stops scanning after reading a number. So with input 123Enter, the '\n' remains in stdin for the next input function like the now non-standard gets(). gets() reads that single '\n' and returns. By adding a space, scanf("%d ", &num); consumes the white-space after the number and does not return until non-white-scape is entered after the number.
When I do the space, it first does scanf then the gets and after that it print the number and print the string.
By adding a space, scanf("%d ", &num); does not return until non-white-space is entered after the number (as in 'a' in the following). Since stdin is usually line buffered, this means input of 2 lines needs to first occur. 123Enter abcEnter.
Recommend to instead use fgets() to read a line of user input.
char str[10*2]; // no need for such a small buffer
int num;
printf("Enter your number : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
sscanf(str, "%d", &num);
printf("%d\n",num);
printf("Enter data : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
fputs(str, stdout);
More robust code would check the results of fgets(), sscanf() and use strtol() rather than sscanf().
The C FAQ covers all these problems with scanf. See Why does everyone say not to use scanf? What should I use instead? and associated entries. Generally you'll use fgets followed by processing the resulting line such as with sscanf and checking that sscanf succeeded. This avoids leaving unparsed input and risking an infinite loop.
int number;
char line[255];
fgets( line, sizeof(line), stdin );
if( sscanf( line, "%d", &number ) != 1 ) {
fputs("That doesn't look like a number.\n", stdin);
}
Note that fgets will read to a newline or as much as your buffer can hold. If the line is larger than your buffer, it might only read part of the line. Next read from input will get the rest of the line. There's ways to avoid this, such as the POSIX getline function, but at least you don't wind up in an infinite loop.
Let's decipher some comments.
Do not ever use gets. Use fgets.
The reason you don't use gets is because there's no way to limit how much is read from stdin. This means the user can overflow the buffer causing havoc.
char buffer[32];
// What the line is more than 31 characters?
gets(buffer);
fgets() takes the size of the buffer and will read that many characters at most. This prevents a buffer overflow.
char buffer[32];
// If there's more than 31 characters it will stop reading.
// The next read of stdin will get the rest of the line.
fgets( buffer, sizeof(buffer), stdin );
"There's no gets() function in C."
Yes, there is a gets() function in C.
Yes, there isn't a gets() function in C.
It depends on which C you're talking about.
Some people when they say "C" mean C11, the current standard. Others when they say "C" mean C99 the previous standard. Some still adhere to C90, the original standard. There is a gets() function in C90. It was deprecated in C99. It was removed from the language in C11.
C compilers and documentation lag very, very, very far behind the standard. Many are still working on full support of C99. If you work to C11 you're going to be very surprised by the lack of support. If you want your code to work on most any compiler, write to C99.
Anyway, don't use gets.
int main(){
char str[10][50],temp[50];
int lim,i,j;
printf("Enter lim: ");
scanf("%d",&lim);
for(i=0;i<lim;++i){
printf("Enter string[%d]: ",i+1);
gets(str[i]);
}
Here the str[0](Enter string[1]: ) can't be read. The reading starts from 'Enter string[2]: '(str[1]).
But if instead of lim, an integer is passed to loop as below, program executes correctly. What may be reason for this scenario ?
int main(){
char str[10][50],temp[50];
int lim,i,j;
for(i=0;i<5;++i){
printf("Enter string: ");
gets(str[i]);
}
Your scanf() for the number has left a newline in the input stream, which will feed the first gets().
Have a look here for help:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
Also, you do not want to use gets() anymore.
Why is the gets function so dangerous that it should not be used?
Firstly don't use gets() use fgets() instead. From the manual page of gets()
Never use gets(). Because it is impossible to tell without knowing the
data in advance how many characters gets() will read, and because
gets() will continue to store characters past the end of the buffer,
it is extremely dangerous to use. It has been used to break computer
security. Use fgets() instead.
Secondaly stdin is line buffered, when you use scanf() like scanf("%d",&lim); and press ENTER, the newline \n char is left into stdin stream that causes gets() to not to read str[0].
For e.g
for(i=0;i<lim;++i){
printf("Enter string[%d]:\n ",i);
fgets(str[i],sizeof(str[i]),stdin);
}
Also note that when you use fgets() it will store \n into buffer at the end. If you don't want \n at the end of str[index] you have to remove it.
Also don't Forget to check the return value of fgets().
For e.g
char *ptr = NULL;
ptr=fgets(str[i],sizeof(str[i]),stdin);
if( ptr != NULL && str[strlen(str[i])-1] == '\n'){
str[strlen(str[i])-1] = '\0'; /* replace \n with \0 */
}
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
I have two questions:
why only when i do space in "%d " --> scanf("%d ", &num); it works?
I tried fflush(stdin) \ _flushall() between the scnaf and the gets and it doesn't works, it skips the gets.
When I do the space, it first does scanf then the gets and after that it print the number and print the string.
void main()
{
char ch, str[10];
int num;
printf("Enter your number : ");
scanf("%d ", &num);
printf("%d\n",num);
gets(str);
puts(str);
system("pause");
}
why only when i do space in "%d " --> scanf("%d ", &num); it works?
scanf("%d", &num); without a space after the "%d", stops scanning after reading a number. So with input 123Enter, the '\n' remains in stdin for the next input function like the now non-standard gets(). gets() reads that single '\n' and returns. By adding a space, scanf("%d ", &num); consumes the white-space after the number and does not return until non-white-scape is entered after the number.
When I do the space, it first does scanf then the gets and after that it print the number and print the string.
By adding a space, scanf("%d ", &num); does not return until non-white-space is entered after the number (as in 'a' in the following). Since stdin is usually line buffered, this means input of 2 lines needs to first occur. 123Enter abcEnter.
Recommend to instead use fgets() to read a line of user input.
char str[10*2]; // no need for such a small buffer
int num;
printf("Enter your number : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
sscanf(str, "%d", &num);
printf("%d\n",num);
printf("Enter data : ");
fflush(stdout);
fgets(str, sizeof str, stdin);
fputs(str, stdout);
More robust code would check the results of fgets(), sscanf() and use strtol() rather than sscanf().
The C FAQ covers all these problems with scanf. See Why does everyone say not to use scanf? What should I use instead? and associated entries. Generally you'll use fgets followed by processing the resulting line such as with sscanf and checking that sscanf succeeded. This avoids leaving unparsed input and risking an infinite loop.
int number;
char line[255];
fgets( line, sizeof(line), stdin );
if( sscanf( line, "%d", &number ) != 1 ) {
fputs("That doesn't look like a number.\n", stdin);
}
Note that fgets will read to a newline or as much as your buffer can hold. If the line is larger than your buffer, it might only read part of the line. Next read from input will get the rest of the line. There's ways to avoid this, such as the POSIX getline function, but at least you don't wind up in an infinite loop.
Let's decipher some comments.
Do not ever use gets. Use fgets.
The reason you don't use gets is because there's no way to limit how much is read from stdin. This means the user can overflow the buffer causing havoc.
char buffer[32];
// What the line is more than 31 characters?
gets(buffer);
fgets() takes the size of the buffer and will read that many characters at most. This prevents a buffer overflow.
char buffer[32];
// If there's more than 31 characters it will stop reading.
// The next read of stdin will get the rest of the line.
fgets( buffer, sizeof(buffer), stdin );
"There's no gets() function in C."
Yes, there is a gets() function in C.
Yes, there isn't a gets() function in C.
It depends on which C you're talking about.
Some people when they say "C" mean C11, the current standard. Others when they say "C" mean C99 the previous standard. Some still adhere to C90, the original standard. There is a gets() function in C90. It was deprecated in C99. It was removed from the language in C11.
C compilers and documentation lag very, very, very far behind the standard. Many are still working on full support of C99. If you work to C11 you're going to be very surprised by the lack of support. If you want your code to work on most any compiler, write to C99.
Anyway, don't use gets.
When i use gets separately this works. But, when i use scanf in my program it does not work. Can anyone explain what I've missed?
#include <stdio.h>
#include <stdlib.h>
int main(){
char a[]="computer";
char b[]={'p','c','\0'};
char c[30];
char d[30];
printf("a=%s,b=%s\n",a,b);
printf("enter a word\n");
scanf("%s",c);
printf("%s",c);
printf("enter a sentence\n");
gets (d);
printf("%s",d);
return 0;
}
gets doesn't skip the white-space characters before starting to read the string while scanf does.
After your first input, there is \n character in the buffer left behind by first scanf call. This \n is read by gets but scanf skips this white-space character.
this can be solved by using a getchar statement after the scanf call.
printf("enter a word\n");
scanf("%s",c);
getchar();
Do not use gets neither scanf (they do not check array bound), instead use fgets.
printf("enter a word\n");
fgets(c, 30, stdin);
printf("%s",c);
printf("enter a sentence\n");
fgets(d, 30, stdin);
printf("%s",d);
Scanf leaves behind "\n"(without quotes) and then gets() function reads only it.
scanf("%s",c) left the Enter or \n in stdin. When gets() executed it consumed that and returned an empty string. gets() reads in all data up to the \n and trims it off before returning.
The format specifiers like %d %s, etc. (all except %n %c %[) and the whitespace format directives like " " direct scanf() to skip leading whitespace. scanf() itself does not skip leading whitespace.
Suggest using fgets() and avoid using gets().
char buf[100];
printf("enter a word\n");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%29s", c); // 29 because c is size 30
printf("%s\n",c);
printf("enter a sentence\n");
fgets(d, sizeof d, stdin);
printf("%s",d);
scanf removes whitespace automatically from before the datum it's trying to get. An exception to this is the character formats (primarily %c), which don't remove whitespace. However, scanf leaves whitespace after the datum. Therefore, you'll need a way to get rid of that. Use
getc(stdin);
you can then continue on your merry way. This page has more documentation on getc.
Well it is a basic question but I seem confused enough.
#include<stdio.h>
int main()
{
char a[100];
printf("Enter a string\n");
scanf("%s",a);
}
Basically the above is what I want to achieve.
If I enter a string
James Bond
then I want that to be stored in array a.
But the problem is because of presence of a blank space in between only James word is stored.
So how can I solve this one.
UPDATE
After the replies given below I understand fgets() would be a better choice. I want to know internal working of fgets as why is it able to store the string with space where as scanf is not able to do the same.
Is this what you need?
freeBSD: http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/stdio/fgets.c?rev=1.14.14.1;content-type=text%2Fplain
open implementation: https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7425&lngWId=3
OWP(dead) http://www.koders.com/c/fid042417FA231704B84308A66E1B82EADEDAB22051.aspx
ReactOS http://www.koders.com/c/fidEB3507945463053CEFCD518EA0CDFF9EB78E24C9.aspx?s=fgets.c#L1
All implementations scans the input file(or stream) until it reaches \n or EOF, or the maxSize param is hit...
scanf reads up until the first whitespace character. The solution is to use fgets, if memory serves me correctly, in your instance it'd be:
fgets(a, 100, STDIN);
It will read up to 100 characters (or the first \n) from standard input and store it in a.
Do not use the gets function ever, even if it looks easier.
Usually scanf breaks the input at whitespace (space, tab, newline, ...).
For example, the input " 5 42 -100" is accepted with scanf("%d%d%d") because each %d strips the leading whitespace. The same behaviour happens with %s.
The only conversion specifiers where the ignoring of leading whitespace doesn't happen are %%, %[ and %c (and, for different reasons, %n)
char input[] = " hello world";
char buf[100];
sscanf(input, "%8c", buf); /* buf contains " hello w" */
sscanf(input, "%8[^o]", buf); /* buf contains " hell" */
The fgets function reads as many characters as there are, up to the nest line break.
I use The Open Group Base Specifications Issue 7 for online documentation
You should use gets(a)/fgets(a, sizeof(a), stdin) instead of sscanf().
Try fgets():
char a[100];
printf("Enter a string\n");
fgets(a, sizeof(a), STDIN);
To learn more about STDIN, check this.