Print Text After Scanf on Same Line in C Programming

Click For Summary
SUMMARY

The discussion centers on printing a percentage sign (%) immediately after a scanf input prompt in C programming. The user initially attempts to use printf and scanf but finds that the % sign only appears after input is provided. A solution is provided that involves using ANSI escape codes to reposition the cursor, allowing the % sign to be displayed on the same line as the input prompt. This method requires terminal support for ANSI codes and proper enabling.

PREREQUISITES
  • Basic understanding of C programming syntax
  • Familiarity with printf and scanf functions
  • Knowledge of ANSI escape codes
  • Experience with terminal behavior and settings
NEXT STEPS
  • Research ANSI escape codes for cursor manipulation in C
  • Explore advanced input handling techniques in C programming
  • Learn about terminal compatibility and settings for ANSI codes
  • Investigate alternative libraries for enhanced console output in C
USEFUL FOR

C programmers, software developers, and anyone interested in improving console input/output formatting in their applications.

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
2K
Replies
9
Views
2K
  • · Replies 1 ·
Replies
1
Views
11K
  • · 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
3K
  • · Replies 1 ·
Replies
1
Views
5K