#include <stdio.h>
int main()
{
int answer;
printf("Please insert your desired budget :"); //normal printf functions.
printf(" $_____\b\b\b\b"); //This should move the curser back 4 spaces.
//The program outputs the line followed with 4 inverted question marks.
scanf("%d", &answer);
printf("So your budget is %d", answer);
return 0;
}
How come the output is 4 inverted question marks? I am using xcode on mac, could that the problem?
You need to run it in a terminal environment that supports \b escape sequences. The console in Xcode must not understand them.
If you run it in the Terminal app, it should be fine.
There is an example in the book [C Primer Plus] 6th Page.91
list3.10 escape.c
/* escape.c -- uses escape characters */
#include <stdio.h>
int main(void)
{
float salary;
printf("\aEnter your desired monthly salary:");/* 1 */
printf(" $_______\b\b\b\b\b\b\b"); /* 2 */
scanf("%f", &salary);
printf("\n\t$%.2f a month is $%.2f a year.", salary,salary * 12.0); /* 3 */
return 0;
}
The author says :
The actual behavior could be different. For instance, XCode 4.6 displays the \a, \b, and \r characters as upside down question marks!
They shows Xcode didn't support the \b
and the Apple Apple Support Communitiesalso shows the situation.
In my Xcode 5.0,it has the same situation.
Related
Working on a simple C program using basic I/O. printf and scanf to get started.
Using Visual Studio 2019 and Eclipse with MinGW.
The program has several printf statements followed by scanf_s to get an input. I was expecting that printf statements would be executed first and then scanf_s would read the keyboard input.
How in Eclipse that's not what happens. Seems that scanf_s is executed first and then printf statements.
#include <stdio.h>
int main(void)
{
int s;
printf("** Service Ticket Center **\n");
printf(" Choose from the following options.\n");
printf(" 1. Create new ticket.\n");
printf(" 2. Update ticket status.\n");
printf(" 3. Delete ticket.\n");
printf(" 4. Find ticket.");
scanf_s("%d", &s);
return 0;
Ran same code in Visual Studio and printf statements were executed first followed by scanf_s as expected. It seems like Eclipse is the issue.
I want to make a quizgame with a countdown. The problem is; when I use system cls all the prints are going. I tried using printf("/ b"). In that case, I can't get data from the user because the system is in the loop.
Can I keep the question output and count down and get input from the user?
Here this is my countdown code:
int v=30;
while(v!=0) {
printf("\n\t%d",v);
v--;
sleep(1);
system("cls");
}
If I understand your question, and you just want to display a countdown in the same location on the screen, then for terminals that support VT100 emulation (and some earlier VTXX versions), you can just use ANSI escapes to control the cursor visibility and a carriage-return ('\r') to return cursor position to the original starting point. If you use the field-width modifier for your integer output, you don't even need the ANSI escape to clear to end-of-line. If you have variable number of characters that are part of your countdown, you can use the ANSI escape to clear to end-of-line to ensure all text is erased each iteration.
For example you could do:
#include <stdio.h>
#include <unistd.h>
int main (void) {
int v = 30;
printf ("\033[?25l"); /* hide cursor */
while (v--) {
printf (" countdown: %2d\r", v); /* print, CR */
fflush (stdout); /* flush stdout */
sleep (1);
}
printf ("\033[?25h\n"); /* restore cursor, \n */
}
If you did have additional text after the countdown number that varied in length with each iteration, you could use:
printf (" countdown: %2d\033[0k\r", v); /* print, clear to end, CR */
which includes the clear to end-of-line escape \033[0k.
The two additional ANSI escapes used above are \033[?25l (hide cursor) and \033[?25h (restore cursor).
The fflush(stdout); is necessary because output in C is line-buffered by default. Without fflush(stdout);, all output would be buffered until a '\n' was encountered -- making all text appear at once.
Give it a try. If you have a VT compatible terminal, it will work fine. But note, the reason ANSI escapes are discouraged is they are not portable. Not all terminals support VT emulation (but a lot do...) See ANSI Escape sequences - VT100 / VT52 for additional escape sequences.
If you are developing a full fledged terminal app with numerous inputs and outputs formatted on the screen, you are better served using a library that provides that capability, such as ncursees etc..
The possible soulution:
I won't put the sleep.
I would ask the user inside the loop and after every answer i would v-- .
#include <stdio.h>
int main (void) {
int v=10;
char *name;
while(v!=0){
printf("Whats your name? ");
scanf("%s", &name);
printf("\nyour name is %s", &name);
printf("\n");
printf("\n\t%d",v);
printf("\n");
v--;
}
return 0;
}
I was instructed to write a game of dice in C language in which the computer and the user act as competing sides of the game. First, a random number is generated by the computer, and then the string "g" command input by the user is accepted to generate the user's random number (simulate to roll a dice once), and compare their values. If the random number obtained by the user is less than that obtained by the computer, output "Sorry, you loss!", if the results is otherwise, output "Congratulations, you won!".
The code:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand((unsigned)time(NULL));
int com_inp = (rand() % (6 - 1 + 1)) + 1;
int user_inp=0;
char ch;
scanf("%c",&ch);
if(ch=='g')
user_inp = (rand() % (6 - 1 + 1)) + 1;
if(user_inp<com_inp)
printf("\n Sorry, you lost!");
else
printf("\n Congratulations, you won!");
printf("\n Computer dice = %d \t User dice = %d",com_inp,user_inp);
return 0;
}
After running on Xcode v12.2, no output is shown. The console is blank.
However, the output is shown if the program is run on Dev-C++(Windows).
Any help would be appreciated.
I don't see anything printed before the scanf. I am not familiar with Dev-C++ on Windows, but in the Xcode console there is no prompt to show you that it is waiting for input, so you might want to put something like:
printf("Enter a number between 1 and 6\n>");
before your scanf.
You may also be running into some line-buffering issues. Try adding \n at then end of each line you are printing.
if(user_inp<com_inp)
printf("\n Sorry, you lost!\n");
else
printf("\n Congratulations, you won!\n");
printf("\n Computer dice = %d \t User dice = %d\n",com_inp,user_inp);
I want to get date of birth in one line:
#include <stdio.h>
int main()
{
int BirthYear,BirthMonth,BirthDay;
printf("Please enter your birth date: ");
scanf("%d",&BirthYear);
printf("/");
scanf("%d",&BirthMonth);
printf("/");
scanf("%d",&BirthDay);
return 0;
}
This is my output:
Please enter your birth date: YYYY
/MM
/DD
But I want to get something like this:
Please enter your birth date: YYYY/MM/DD
In output, it goes to next line after each scanf() without using \n.
I use VS Code for IDM.
Here is a workaround using ansi control characters. I would not do like this, but just to show that it is possible:
#define PREVLINE "\033[F"
#define MSG "Please enter your birth date: "
int main(void) {
int BirthYear,BirthMonth,BirthDay;
printf(MSG);
scanf("%d",&BirthYear);
printf(PREVLINE MSG "%d/", BirthYear);
scanf("%d",&BirthMonth);
printf(PREVLINE MSG "%d/%d/", BirthYear, BirthMonth);
scanf("%d",&BirthDay);
printf("You entered: %d/%d/%d\n", BirthYear, BirthMonth, BirthDay);
}
Please note that this is not portable. The terminal needs to support this in order to work. AFAIK there's no 100% portable way to achieve this.
If you want to do this stuff for real, then I recommend taking a look at the ncurses library
Note:
Always check the return value for scanf to detect errors.
Note2:
It may be a good idea to add fflush(stdout); after each printf statement.
I actually wrote another answer today about ascii control characters. It might be interesting: https://stackoverflow.com/a/64549313/6699433
You can explicitly specify that the three input numbers should be separated by a '/' character by adding that character in the format specifier for the scanf function.
Then, you can ensure that the user gave valid input by checking the value returned by scanf (which will be the number of items successfully scanned and assigned); if that value is not 3, then you will (probably) need to clear any 'leftover' characters in the input buffer, using a getchar() loop until a newline (or end-of-file) is found:
#include <stdio.h>
int main()
{
int BirthYear, BirthMonth, BirthDay;
int nIns = 0, ch;
while (nIns != 3) {
printf("Enter D.O.B. (as YYYY/MM/DD): ");
nIns = scanf("%d/%d/%d", &BirthYear, &BirthMonth, &BirthDay);
while ((ch = getchar() != '\n') && (ch != EOF))
; // Clear remaining in-buffer on error
}
printf("Entered data were: %d %d %d!\n", BirthYear, BirthMonth, BirthDay);
return 0;
}
Expanding on my comment...
The problem you're running into is that you have to hit Enter for each input, which writes a newline to the terminal screen. You can't avoid that.
And unfortunately, you can't overwrite the newline on the screen with a '\b'; you can only backspace up to the beginning of the current line, not to a previous line.
You basically can't do what you want with vanilla C - the language only sees byte streams, it has no concept of a "screen".
There are some terminal control sequences you can play with to reposition the cursor after sending the newline; I don't know how well those will work for you.
Beyond that, you'll need to use a library like ncurses.
#include <stdio.h>
int main()
{
int BirthYear,BirthMonth,BirthDay;
printf("Please enter your birth date: ");
scanf("%d/%d/%d",&BirthYear,&BirthMonth,&BirthDay);
return 0;
}
You can take multiple values from scanf which are then separated by any text you like (in this case /s).
You could use fflush(3) (in particular before all calls to scanf(3)) like in
printf("Please enter your birth date: ");
fflush(NULL);
but you should read this C reference website, a good book about C programming such as Modern C, and the documentation of your C compiler (perhaps GCC) and debugger (perhaps GDB).
Consider enabling all warnings and debug info in your compiler. With gcc that means compiling with gcc -Wall -Wextra -g
Be aware that scanf(3) can fail.
Your code and problem is surely operating system specific.
On Linux consider using ncurses (for a terminal interface) or GTK (for a graphical interface). Read also the tty demystified, then Advanced Linux Programming and syscalls(2) and termios(3).
You might also consider using ANSI escape codes, but be aware that in 2020 UTF-8 should be used everywhere.
This is the code:
#include <stdio.h>
int main()
{
int i = 0;
while(getchar() != '\n') {
printf("\n%d\n", i);
i++;
}
printf("second printf: %d\n", i);
return 0;
}
The expected ouput after I press enter only is:
second printf: 0
instead of:
0
second printf: 1
Why is this happening ?
I am on linux Ubuntu MATE.
So I got some information about anas firari's environment by reading his other questions. This involves some measure of physic debugging.
You are getting input of \r\n when you type a newline because your terminal is in raw mode. Older shells used to choke on this by treating \r as something that isn't whitespace, but newer ones actually work ok.