4

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: What happening

     Enter number: 23
     You entered 23

What I want to achieve: What i want to achieve

     Enter number: 23 , You entered 23
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
AhmetEnesKCC
  • 69
  • 2
  • 8

1 Answers1

5

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.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83