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.
Related
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.
I'm trying to use the EOF function but it doesn't work as I expect it. In the debugger mode it doesn't detect the second "scanf" function and just carries on. It keeps on missing out the "scanf" function now and then. Code is posted below
int main() {
char tempString;
int i = 0;
printf("Enter your letter\n");
scanf_s("%c", &tempString);
while (tempString != EOF) {
printf("You entered:%c\n", tempString);
scanf_s("%c", &tempString);
}
}
I have also tried it using the getchar() function but the same thing occurs, code is posted below:
int main() {
char tempString;
int i = 0;
printf("Enter your letter\n");
while ((tempString = getchar()) != EOF) {
printf("You entered:%c\n", tempString);
}
}
Thanks for reading
EDIT:
Firstly you omitted the length argument required by scanf_s for %c and %s formats.
Second, the %c format takes the next character from the input buffer. At the second (and subsequent) entries there was a newline left in the input buffer from the first input. Adding a space before the %c format specifier cleans off that leading whitespace.
Other formats, such as %s and %d do ignore leading whitespace, but not %c.
Thirdly, with scanf the use of EOF is not the way to go, you should control the loop with the return value from scanf which tells you the number of items successfully read.
This program starts by using scanf_s. The second entry ignores the newline after the first entry.
Then it moves to using getchar. In this test the function return value is int, so that's my data type here. That way EOF (-1) won't conflict with any required character data. Note that getchar starts by reading the newline left after the previous scanf_s (which only ignores leading whitespace.
#include <stdio.h>
int main(void)
{
char ch_scanf; // char type
int ch_getchar; // int type
printf("Using scanf_s\n");
if (scanf_s(" %c", &ch_scanf, 1) == 1) { // consumes any leading whitespace
printf("scanf_s value: %d\n", ch_scanf);
}
if (scanf_s(" %c", &ch_scanf, 1) == 1) { // consumes any leading whitespace
printf("scanf_s value: %d\n", ch_scanf);
}
printf("\nUsing getchar\n");
while ((ch_getchar = getchar()) != EOF) {
printf("getchar value: %d\n", ch_getchar);
}
return 0;
}
Sample session:
Using scanf_s
A
scanf_s value: 65
B
scanf_s value: 66
Using getchar
getchar value: 10
C
getchar value: 67
getchar value: 10
^Z
Finally if you want to use the standard library function scanf without MSVC ticking you off, you can do it like this
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
try this
#include <stdio.h>
int main(void) {
char tempString;
printf("Enter your letter\n");
while (scanf_s("%c%*c", &tempString, 1) != EOF) {//%*c for consume newline, 1 is buffer size
printf("You entered:%c\n", tempString);
}
return 0;
}
int tempString;//int for check EOF
printf("Enter your letter\n");
while ((tempString = getchar()) != EOF) {
printf("You entered:%c\n", tempString);
getchar();//consume newline
}
The behaviour of scanf() function in C
Is to read the input from the keyboard buffer till it encounters EOF (ie; till we
press enter key)
In general, it is not advisable to use "%c" in C to read an input character because
The value is collected in keyboard buffer till we hit enter and we could not restrict user entering single character
So, the best way to obtain a character is by using getchar() function.
In the program you have provided you can use any other character to check for end and not EOF since it is used in scanf() implementation to mark the input end.
You may other keys like esc to check for the end
#include <stdio.h>
#include <stdlib.h>
#define esc 27
int main()
{
char ch;
while((ch = getchar()) != esc) {
//print the entered character here
}
}
To know in depth about scanf() implementation look into this scanf() source code
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/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...
when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
int c;
while((c = getchar()) != '\n' && c != EOF && c != ' ') ;
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
You can also use a getch() instead of getchar() to avoid pressing enter key.
#include <stdio.h>
#include <conio.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getch();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getch();
printf("the char is: %c\n",q);
return 0;
}
When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH
#define FLUSH while(getchar() != '\n')
to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.
p=getchar();
printf("the char is: %c\n",p);
FLUSH;
it will read the newline then stops because the condition within the while statement no longer holds.
Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.
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.