#include <stdio.h>
int main()
{
int r;
printf("radius is : cm");
scanf("%d",&r);
printf(" radius is %d cm",r);
}
This is the code I wrote and it is printing ' radius is : cm (input) ' but I want the PC to print it as ' radius is : (input) cm ' I tried it by using one more print statement after the scan statement but the ' cm ' is getting printed after user giving the input.
Tl:dr how to take the input from between the sentence of a print statement
CodePudding user response:
This can't really be done cleanly without a terminal library, however you can come close by adding spaces between ":" and "cm" and printing backspaces at the end of the line to push the cursor back:
#include <stdio.h>
int main()
{
int r;
printf("radius is : cm\b\b\b\b\b\b\b\b");
scanf("%d",&r);
printf(" radius is %d cm",r);
}
Output:
radius is : cm
^
|--cursor is here
The caveat is that if you type more characters than expected they will overwrite "cm".
CodePudding user response:
There is simply no good way to do this in a simple manner. The preferred way would be digging into libraries like ncurses
, but using that would be a bit too far for this question I think.
One thing that "works" but would be considered bad practice and definitely comes with its drawbacks is to simply print the backspace character.
printf("radius is : cm\b\b\b\b\b\b\b");
scanf("%d",&r);
This will keep "cm" in a fixed position, but you can overwrite it with the input and then it will not come back. If you want it to move as you enter more characters, then you have some (a lot of) work to do.
If your goal is to be clear about the unit, then consider wording the input differently. Like "Enter radius in cm: " or "Radius (cm) : " or something like that.
Here is an example of what it takes if you want "cm" to float back and forth as you're typing. Note that this is NOT guaranteed to work. It depends on the console you're printing to.
void clearline() {
printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
printf(" ");
printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
}
int main()
{
int ch;
char buf[200] = {0};
int index = 0;
printf("Enter radius: cm\b\b\b");
while((ch = getchar()) != EOF && ch != '\n') {
if(ch == '\b' && index != 0) buf[--index] = 0;
buf[index ] = ch;
clearline();
printf("Enter radius: %s cm", buf);
fflush(stdout);
}
int r = atoi(buf);
printf(" radius is %d cm", r);
}