Print Text After Scanf on Same Line in C Programming

Click For Summary
To print text after a scanf statement on the same line in C, you can use ANSI escape codes to reposition the cursor. This allows you to display additional characters, like a percentage sign, immediately after the input prompt. The method requires that your terminal supports ANSI codes and that they are enabled. The original code does not display the percentage sign until after the input is provided, which is not the desired outcome. Using ANSI codes effectively addresses this issue.
jaydnul
Messages
558
Reaction score
15
How do you print text after a scanf statement on the same line? This is what i need the output to look like:

Enter a number here: _%

The _ is the scanf waiting for input. Now when i write the code like this:

printf("Enter a number here: ");
scanf("%d", &x);
printf("%\n");

It won't put the % sign until after i input a value. How should i rewrite this to achieve what I need? thanks in advance!
 
Physics news on Phys.org
lundyjb said:
How do you print text after a scanf statement on the same line? This is what i need the output to look like:

Enter a number here: _%

The _ is the scanf waiting for input. Now when i write the code like this:

printf("Enter a number here: ");
scanf("%d", &x);
printf("%\n");

It won't put the % sign until after i input a value. How should i rewrite this to achieve what I need? thanks in advance!

You can only do that if you use ansi screen codes to reposition the cursor after you've written the prompt line:

http://courseweb.stthomas.edu/tpsturm/private/notes/qm300/ANSI.html

These work only if your terminal window supports them and if its been enabled. I've used them in my awk scripts a lot.
 
Alright. Thanks man
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 1 ·
Replies
1
Views
11K
Replies
9
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K