Taking a string input using gets() function in C [duplicate] - c

I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!

Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...

scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too

scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.

you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.

scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}

The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm

Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}

Related

Why does the number 10 get output in each iteration and how can I fix this?

I have a for loop, which I want to get the input from the user and print the associated ascii value. But it only asks for the user input in the second iteration, which is followed and preceded by the output 10. I tried to get rid of new-line characters, but it still prints out 10.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: \n");
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
Maybe simpler (though using scanf() for user input is not recommended)
scanf(" %c", &character);
// ^ skip otional leading whitespace
Your whole program using fgets() for user input (and my indentation, spacing, style; sorry)
#include <stdio.h> // printf(), fgets()
#include <stdlib.h> // strtol()
int main(void) {
int number;
char buffer[100]; // space enough
printf("Enter the number:");
fgets(buffer, sizeof buffer, stdin);
number = strtol(buffer, 0, 10); // error checking missing
for (; number > 0; number--) {
printf("Give a char: ");
fgets(buffer, sizeof buffer, stdin); // reuse buffer, error checking missing
if (buffer[0] != '\n') {
printf("The associated ascii value of '%c' is %i.\n", *buffer, *buffer);
}
}
return 0;
}
This should solve your problem. getchar() will read the extra newline character from buffer.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: ");
getchar();
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
regarding;
scanf("%c", &character);
the first time through the loop the '\n' is input.
on all following passes through the loop, the scanf() fails, so the value in character does not change.
This is a prime example of why your code should be error checking.
for instance, to error check the call to scanf():
if( scanf("%c", &character) != 1 )
{
fprintf( stderr, "scanf for a character failed\n" );
break;
}
the 1 is because the scanf() family of functions returns the number of successful: input format conversion specifiers or EOF and it is best to assure the 'positive' status.

Why is scanf skipping the input here? [duplicate]

This question already has answers here:
Using fflush(stdin)
(7 answers)
Parsing input with scanf in C
(5 answers)
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
#include <stdio.h>
int main()
{
char another;
int num;
do
{
printf("enter the number");
scanf("%d", &num);
printf("square of%d is %d\n", num, num * num);
printf("want to check another number y/n");
fflush(stdin);
scanf("%c", &another);
} while (another == 'y');
return 0;
}
In the above code, the second scanf() is not getting executed and hence the console is not accepting input.
According to the standard, flushing stdin is undefined behaviour. See Using fflush(stdin) for more information.
When you enter a number for the first scanf, its always followed by a newline. %d only takes the integer value and the newline is still left in the input buffer. So the subsequent scanf ends up consuming that character and your loop terminates due to another=='y' being false. (another has '\n').
Following is one of the ways to solve the problem. Use a %c along with %d to capture newline and ignore it.
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
printf("%c", another);
}while (another=='y');
return 0;
}
if you add the statement
fseek(stdin, 0, SEEK_END);
it will move the stdin pointer to the end of the file so any extra character will be omitted. then write the second scanf. I mean:
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
fseek(stdin, 0, SEEK_END);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
fseek(stdin, 0, SEEK_END);
printf("%c", another);
}while (another=='y');
return 0;
}
Cause of the char input before scanf dont work
remove the fflush and add a space to <<"%c">>
like this: scanf(" %c",&another);
#include<stdio.h>
int main(){
char another;
int num;
do
{
printf("enter the number ");
scanf("%d",&num);
printf("square of %d is %d\n",num,num*num);
printf("want to check another number y/n ");
scanf(" %c",&another);
}while (another=='y');
return 0;
}
This works great
First of all fflush; flushes the output buffer of a stream, so you should not be using it here. The reason why the second scanf is not working is because you are trying to read a 1-bit character which in this case always getting the value of \0 after the second printf statement. Hope this helped.

Why does this scanf in a while loop work?

I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dend, dsor, q, r;
char c;
while(c!='n')
{
printf("enter dividend: ");
scanf("%d", &dend);
printf("enter divisor: ");
scanf("%d", &dsor);
q=dend/dsor;
r=dend%dsor;
printf("quotient is %d\n", q);
printf("remainder is %d\n", r);
scanf("%c", &c);
printf("continue? (y/n)\n");
scanf("%c", &c);
}
system("PAUSE");
return 0;
}
FWIW, your code invokes undefined behavior. In the part
char c;
while(c!='n')
c is an uninitialized local variable with automatic storage and you're trying to use the value of c while it is indeterminate.
That said, first scanf("%c", &c); is used to eat up the newline present in the input buffer due to the press of enter key after previous input. You can read about it in details in another post.

Why procedure if in C doesn't work with char

I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,

Taking some string input from user with C

I am not too familiar with C syntax. I need to process some data based on user input. Although I processed the data successfully but I am stuck at user input section. I removed the unnecessary data processing section and made a simple example of how I am taking the user input. Can anyone tell me what's the problem with below code :
int i, number;
char *str;
str=(char*)malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
scanf ("%[^\n]%*c", str);
printf("%s", str);
}
Output:
"Enter count : " appears fine, but whenever I provide some value and hit enter it's showing me only 'count' number of Enter string: without enabling user to enter the string.
For example -
Enter count : 2
Enter string:
Enter string:
But if I discard the count input section and provide any fixed value, like
for(i=0; i<5; i++)
it works fine
Thanks in advance
FYI, there is no issue in for(i=0; i<number; i++), problem is in scanning logic.
Actually, scanf ("%[^\n]%*c", str); is not right. you should use %s to read strings, not %c, which reads a single character, including the ENTER (newline).
Rather, i would suggest, use fgets() for inputs. It's a whole lot better in every way. Check the man page here.
Maybe you can use something like
//Dummy code
int i, number;
char *str;
printf("Enter count : ");
scanf("%d", &number);
str=malloc(number*sizeof(char)); //yes, casting not required
fgets(str, (number-1), stdin ); //"number" is used in different context
fputs(str, stdout);
EDIT:
Working code
#include <stdio.h>
#include <stdlib.h>
#define SIZ 1024
int main()
{
int i, number;
char * str = malloc(SIZ * sizeof (char));
printf("Enter the number :\n");
scanf("%d", &number);
getc(stdin); //to eat up the `\n` stored in stdin buffer
for (i = 0; i < number; i++)
{
printf("Enter the string %d :", (i+1));
fgets(str, SIZ-1, stdin);
printf("You have entered :");
fputs(str, stdout);
}
return 0;
}
scanf("%s",str); Use this instead of the code you are using to take string inputs in a character array.
There is a newline character \n after entering count value which is picked up by %c in your scanf()
Just use %s to scan strings as shown below.
scanf("%s",str);
If there are spaces in your input.
Then do
char c[50];
fgets(c,sizeof(c),stdin);
Check the below code:
#include <stdio.h>
#include<stdlib.h>
int main(){
int i, number;
char *str;
str=malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d%*c", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
fgets(str,1000,stdin);
printf("%s", str);
}
}

Resources