PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

[FIXED] How to use printf() and scanf() in C without going to the next line?

 August 17, 2022     c, newline, output, scanf     No comments   

Issue

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.


Solution

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



Answered By - klutt
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing