In my C program, I call fgets() twice to get input from the user. However, on the second call of fgets() (which is in a function), it doesn't wait for the input to be taken, it just skips over it as if it didn't even ask for it. Here is my code (shortened down a bit):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARE_EQUAL 0
void rm_nl(char *c, int s);
float ctof();
float ftoc();
int main()
{
char str[2]; // Setting vars
float result;
printf("Type 'C' or 'F': "); // Prompt
fgets(str, 2, stdin); // <-- First fgets
rm_nl(str, 2); // rm_nl() removes the newline
// from input
printf("\n");
if(strcmp(str, "C") == ARE_EQUAL || strcmp(str, "c") == ARE_EQUAL)
{
result = ctof(); // Compares strings and calls
printf("%.2f\n", result); // function conditionally
}
else
{
result = ftoc();
printf("%.2f\n", result);
}
return 0;
}
float ctof() // One of the two functions
{ // (they are almost the same)
char input[64];
float fahr, cels; // Local vars
printf("Type in a Celsius value: "); // Prompt
fgets(input, 64, stdin); // <-- Second fgets
rm_nl(input, sizeof(input));
// Yadda yadda yadda
}
// Second function and rm_nl() not shown for readability
This program would output something like:
Type 'C' or 'F': (value)
and then...
Type a Celsius value: 57.40 (I don't type this)
(Program terminates)
It fills in the 57.40 without me even typing it! What should I do differently?
fgets(str, 2, stdin);
You're providing too little space for fgets. You only allow it to read one character (since 2 includes the 0-terminator).
The newline will always be left in the input buffer so the next stdio operation will read it.
Related
How can I print on the same line as input?
This is my code
#include <stdio.h>
int main() {
int number;
printf("Enter number: ");
scanf("%d", &number);
printf("You entered: %d",number);
return 0;
}
What's happening:
Enter number: 23
You entered 23
What I want to achieve:
Enter number: 23 , You entered 23
Using the 'standard' input routines (those defined in <stdio.h>, such as scanf and getchar) will wait until you hit the "Enter" key before processing your input – and that "Enter" will be echoed as a newline (can't be avoided).
But you can use the getch() function (defined in <conio.h>); this will not echo the keys/characters you input so, when you hit "Enter", the newline is not 'reflected' on the console. However, you will then have to manually echo any other characters you type, and save them to an input buffer; you can then read your integer from that buffer using the sscanf function.
Here's a short example that does what you ask:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char buffer[256] = ""; // Space for our input string
printf("Enter number: ");
int in;
while ((in = getch()) != '\r') { // Read until we see the "Enter" key ...
char out = (char)(in);
printf("%c", out); // We need to manually "echo" the input character...
buffer[strlen(buffer)] = out; // ... and add that to our input buffer
if (strlen(buffer) == 255) break; // Prevent buffer overflow!
}
int number;
sscanf(buffer, "%d", &number); // Read number from buffer ...
printf(" , You entered: %d", number); // ... and print it (on the same line)
return 0;
}
Note: There are more error-checks that you could (should) add to this code (like checking the return value of scanf to make sure a valid integer is given); however, what I have shown 'emulates' your original code, but without echoing the newline.
My code:
#include <stdio.h>
#include <math.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a);
puts("enter");
gets(b);
puts("enter");
puts(a);
puts(b);
}
return 0;
}
Output:
1
enter
enter
surya (string entered by user)
enter
surya (last puts function worked)
How can I use “gets” function many times in C program?
You should never ever use gets() in your program. It is deprecated because it is dangerous for causing buffer overflow as it has no possibility to stop consuming at a specific amount of characters - f.e. and mainly important - the amount of characters the buffer, a or b with each 10 characters, is capable to hold.
Also explained here:
Why is the gets function so dangerous that it should not be used?
Specially, in this answer from Jonathan Leffler.
Use fgets() instead.
Also the defintion of a and b inside of the while loop doesn´t make any sense, even tough this is just a toy program and for learning purposes.
Furthermore note, that scanf() leaves the newline character, made by the press to return from the scanf() call in stdin. You have to catch this one, else the first fgets() thereafter will consume this character.
Here is the corrected program:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if(scanf("%d",&t) != 1)
{
printf("Error at scanning!");
return 1;
}
getchar(); // For catching the left newline from scanf().
while(t--)
{
puts("Enter string A: ");
fgets(a,sizeof a, stdin);
puts("Enter string B: ");
fgets(b,sizeof b, stdin);
printf("\n");
puts(a);
puts(b);
printf("\n\n");
}
return 0;
}
Execution:
$PATH/a.out
2
Enter string A:
hello
Enter string B:
world
hello
world
Enter string A:
apple
Enter string B:
banana
apple
banana
The most important message for you is:
Never use gets - it can't protect against buffer overflow. Your buffer can hold 9 characters and the termination character but gets will allow the user to typing in more characters and thereby overwrite other parts of the programs memory. Attackers can utilize that. So no gets in any program.
Use fgets instead!
That said - what goes wrong for you?
The scanf leaves a newline (aka a '\n') in the input stream. So the first gets simply reads an empty string. And the second gets then reads "surya".
Test it like this:
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a); // !!! Use fgets instead
puts("enter");
gets(b); // !!! Use fgets instead
puts("enter");
printf("|%s| %zu", a, strlen(a));
printf("|%s| %zu", b, strlen(b));
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
|| 0|surya| 5
So here you see that a is just an empty string (length zero) and that b contains the word "surya" (length 5).
If you use fgets you can protect yourself against user-initiated buffer overflow - and that is important.
But fgets will not remove the '\n' left over from the scanf. You'll still have to get rid of that your self.
For that I recommend dropping scanf as well. Use fgets followed by sscanf. Like:
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
So the above code will automatically remove '\n' from the input stream when inputtin t and the subsequent fgets will start with the next word.
Putting it all together:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
while(t--)
{
puts("enter");
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
if (fgets(b,sizeof b, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
printf("%s", a);
printf("%s", b);
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
surya
whatever
Final note:
fgets will - unlike gets - also save the '\n' into the destination buffer. Depending on what you want to do, you may have to remove that '\n' from the buffer.
Even though I use this condition in scanf("[^\n]s", x), or "%34[^\n]", or %127s, I'm unable to get answers correctly. Is there any problem with the scanf area or in some other part....
#include <stdio.h>
int main()
{
int i = 4;
double d = 4.0;
char s[] = "hello ";
int a;
double b;
unsigned char string_2[100];
scanf("%d",&a);
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
printf("%d",a+i);
printf("\n%lf",d+b);
printf("\n%s",s);
printf("%s",string_2);
return(0);
}
Don't use scanf like that.
In this:
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
The first scanf reads a number from the input, but has to wait for your terminal to give the program a complete line of input first. Assume the user 123, so the program reads 123\n from the OS.
scanf sees the newline that is not part of the number any more, and stops at that leaving the newline in the input buffer (within stdio). The second scanf tries to read something that is not newlines, but can't do that, since the first thing it sees is a newline. If you check the return value of the scanf calls, you'll see that the second scanf returns a zero, i.e. it couldn't complete the conversion you asked for.
Instead, read full lines at a time, with fgets or getline:
#include <stdio.h>
int main(void)
{
char *buf = NULL;
size_t n = 0;
double f;
getline(&buf, &n, stdin);
if (sscanf(buf, "%lf", &f) == 1) {
printf("you gave the number %lf\n", f);
}
getline(&buf, &n, stdin);
printf("you entered the string: %s\n", buf);
return 0;
}
For a longer discussion, see: http://c-faq.com/stdio/scanfprobs.html
I was working on this sample exercise, and everything works as I would like it to, but there is one behavior I don't understand.
When providing input: if I make consecutive invalid entries everything seems to work great. But if I enter a number different from 1,2,3 in the case of the first question, or 1,2 in the case of the second question, the program just sits there until a new input is given. If another invalid entry is made, it goes back to the error "invalid entry" message, and if an appropriate number is entered, everything moves along fine.
I do not understand why it stops to wait for a second input...anyone?
Thanks guys.
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
printf("%s",prompt);
while (scanf("%d", &value) !=1)
{
printf("Your entry is invalid.\nGive it another try: %s", prompt);
getchar();
scanf("%d", &value);
}
return value;
}
int main() {
int wood_type, table_size, table_price;
printf("Please enter " );
wood_type = getInt("1 for Pine, 2 for Oak, and 3 for Mahogany: ");
printf("Please enter ");
table_size = getInt("1 for large, 2 for small: ");
printf("\n");
switch (wood_type) {
case 1:
table_price = (table_size == 1)? 135:100;
printf("The cost of for your new table is: $%i", table_price);
break;
case 2:
table_price = (table_size == 1)? 260:225;
printf("The cost of for your new table is: $%i", table_price);
break;
case 3:
table_price = (table_size == 1)? 345:310;
printf("The cost of for your new table is: $%i", table_price);
break;
default:
table_price = 0;
printf("The cost of for your new table is: $%i", table_price);
break;
}
}
You most likely need to flush your input buffer (especially with multiple scanf calls in a function). After scanf, a newline '\n' remains in the input buffer. fflush does NOT do this, so you need to do it manually. A simple do...while loop works. Give it a try:
edit:
static int getInt(const char *prompt)
{
int value;
int c;
while (printf (prompt) && scanf("%d", &value) != 1)
{
do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input
printf ("Invalid Entry, Try Again...");
}
return value;
}
The blank line you get if you enter nothing is the normal behavior of scanf. It is waiting for input (some input). If you want your routine to immediately prompt again in the case the [Enter] key is pressed, then you need to use another routine to read stdin like (getline or fgets). getline is preferred as it returns the number of characters read (which you can test). You can then use atoi (in <stdlib.h>) to convert the string value to an integer. This will give you the flexibility you need.
example:
int newgetInt (char *prompt)
{
char *line = NULL; /* pointer to use with getline () */
ssize_t read = 0; /* number of characters read */
size_t n = 0; /* numer of chars to read, 0 no limit */
static int num = 0; /* number result */
while (printf ("\n %s ", prompt) && (read = getline (&line, &n, stdin)) != -1)
{
if ((num = atoi (line)))
break;
else
printf ("Invalid Input, Try Again...\n");
}
return num;
}
If some invalid input is entered, it stays in the input buffer.
The invalid input must be extracted before the scanf function is completed.
A better method is to get the whole line of input then work on that line.
First, put that input line into a temporary array using fgets(),
then use sscanf() (safer than scanf because it guards against overflow).
#include <stdio.h>
int main(int argc, const char * argv[]) {
char tempbuff[50];
int result, d , value;
do
{
printf("Give me a number: ");
fgets( tempbuff, sizeof(tempbuff), stdin ); //gets string, puts it into tempbuff via stdin
result = sscanf(tempbuff, "%d", &value); //result of taking buffer scanning it into value
if (result < 1){ //scanf can return 0, # of matched conversions,
//(1 in this case), or EOF.
printf("You didn't type a number!\n");
}
}while (result < 1);
//some code
return 0;
}
Knowledge from: http://www.giannistsakiris.com/2008/02/07/scanf-and-why-you-should-avoid-using-it/
I am refreshing my C skills and am having a little bit of difficulty with a simple program I am working on. Here it is:
#include <stdio.h>
#include <ctype.h> // for isdigit()
#include <stdlib.h> // for atoi()
int main (int argc, const char * argv[])
{
// first read in # of file events to follow, if not an int,
// complain & abort
char *input;
input = malloc(2); // input[0] holds the character
// input[1] holds the terminator
int numLines = 0;
scanf("%c", &input);
if (isdigit((int)input)) {
numLines = atoi(input);
} else {
printf("First line of input must be int type! Aborting...\n");
return 1;
}
//...
}
The problem is, then even when I enter a number (i.e. 2) it still outputs the aborting message and exits:
2
First line of input must be int type! Aborting...
I am having a hard time figuring out why it behaves like it is and what I should do to fix the problem. Shouldn't the '%c' specifier tell the compiler to take in the input as an ANSI character and then isdigit() should properly interpret that to be an integer?
Thanks in advance!
Change this:
scanf("%c", &input);
if (isdigit((int)input)) {
to this:
scanf("%c", input);
if (isdigit(input[0])) {
As it is right now, you are overwriting the pointer itself, rather writing to the allocated memory.
Also, you need to null-terminate:
input[1] = '\0';
Furthermore, it's not necessary to allocate memory for this. You can get away with just:
char input[] = " ";
scanf("%c", input);
if (isdigit(input[0])) {
numLines = atoi(input);
or alternatively:
char input;
scanf("%c", &input);
if (isdigit(input)) {
numLines = input - '0';
Change your code to:
char input[2] = {0}; // <<-- you don't clear the memory after malloc,
// your atoi might fail. No need for malloc here.
int numLines = 0;
scanf("%c", &input[0]);
if (isdigit((int)input[0])) {
numLines = atoi(input);
} else {
printf("First line of input must be int type! Aborting...\n");
return 1;
}
And you're good. No need to dynamically allocate here, its just a waste of effort.
When you pass &input to scanf, you are passing a pointer to a char *. You should just pass the pointer itself, that is,
scanf("%c", input);