1

I have written a simple C program which takes input from the user using code similar to the following:

printf("Please enter number one: ");
scanf("%i", &numberOne);
printf("Please enter number two: ");
scanf("%i", &numberTwo);
...

This all works fine when the program is run - the user is prompted for input, with each input prompt appearing on a separate line (presumably because the user hits the Return key to indicate they have finished entering their input on the previous line). For example:

Please enter number one:
Please enter number two:

However, when I redirect a text file into the program as the input (for testing) using ./myProgram < inputText.txt all the input prompts appear on a single line, I am guessing because there is no Return key being pressed since all the inputs come from the text file:

Please enter number one: Please enter number two:

Is it possible for the prompts to appear each on their own line?

Thanks for any help!

2 Answers 2

2

When the program is run interactively, the user input is echoed on the screen. When you redirect standard input into the program, that input isn't echoed. So in order to get the newlines in the latter case and not the former case, you have to detect that case and do something different depending on where you're getting input from.

Thankfully, that's not very difficult here provided that you're on a POSIX system. Add:

#include <unistd.h>

and then after each scanf add:

if (!isatty(STDIN_FILENO))
    printf("\n");

This checks whether standard input is connected to a terminal. If not (if, for example, it's redirected input from a file), it prints a newline.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, that's perfect :) I have also done a modification so it's now printf("%i\n", numberOne) so that it will also echo the input from the file to the screen.
0

You can print newline after scanf to get more pretty printed output. Side-effect is you will see additional blank line when you are giving the input.

printf("Please enter number one: ");
scanf("%i", &numberOne);
printf("\n");
printf("Please enter number two: ");
scanf("%i", &numberTwo);
printf("\n");
...

1 Comment

Thanks for that. I had already tried your suggestion previously and gotten the extra blank line when giving the input manually - I was hoping to avoid that occurring if possible...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.