1

How to print in same line after scanf?

my code:

int ui;

char up_from_down=179;

printf("%c",up_from_down);scanf("%d",&ui);printf("1                                              %c\n",up_from_down);

I don't know or explain well how I want it to be

so i add ss

ss now:enter image description here

I want it to be:enter image description here

tadas
  • 31
  • 6
  • Does this answer your question? [Why does printf not flush after the call unless a newline is in the format string?](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Chris Turner Nov 22 '19 at 17:11

1 Answers1

1

If your terminal supports ANSI Escape Codes, this will move the cursor up one line and then to column 10 and resume printing on the same line as the input for ui.

#include <stdio.h>

int main()
{
    int ui;
    char up_from_down=179;

    printf("%c",up_from_down);
    scanf("%d",&ui);
    printf ( "\033[1A");//move cursor up one line
    printf ( "\033[10C");//move cursor 10 places
    printf("1                                              %c\n",up_from_down);
    return 0;
}

If you want the printing to more closely follow the input, use %n to capture the number of characters processed by scanf and use that value in the ANSI Escape Code.

#include <stdio.h>

int main()
{
    int ui = 0;
    int col = 0;
    char up_from_down=179;

    printf ( "%c", up_from_down);
    fflush ( stdout);//no newline in printf so force printing
    if ( 1 == scanf ( "%d%n", &ui, &col)) {
        col += 2;
        printf ( "\033[1A");//move cursor up one line
        printf ( "\033[%dC", col);//move cursor to col
        printf("1                                              %c\n",up_from_down);
    }
    return 0;
}
user3121023
  • 6,995
  • 5
  • 14
  • 13