anechkayf
anechkayf

Reputation: 567

Redirect C output to a txt file

I am redirecting program output to a txt file and entering the values prompted by the main function: terminal capture

I expected my output.txt file to have the following data:

Enter float1: 2.4
Enter float1: 4.6

But instead, it has this:

Enter float1: 
Enter float1: 

Here is my main function:

printf("Enter float1: ");
scanf("%f", &float1);
printf("Enter float2: ");
scanf("%f", &float2);

Can anyone please help to redirect inputted values as well? I researched the question but I couldn't find anything that would solve the problem. I tried redirection stderr to see if the values are printed there but it gave me an empty file.

Upvotes: 0

Views: 603

Answers (3)

Ben
Ben

Reputation: 195

Change your main to:

printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);
printf("Enter float2: ");
scanf("%f", &float2);
printf("%f\n", float2);

On a side note, if you're confused about redirection, printf is a modified version of fprintf. Printing to the console is just so common there's a function for it. Saying printf("%f\n", float1) is the same as fprintf(stdout, "%f\n", float1). Same goes for scanf vs. fscanf. Redirecting output allows you to keep your printf statements in your code, yet still print to a file. Else you would have manually change them all to fprintf which would be a pain.

Upvotes: 1

Risinek
Risinek

Reputation: 435

The user input is stdin but you are redirecting only stdout to file. Hence you will see in the output.txt only what your program prints to stdout. If you want to print entered values, you have to print them after scanf.

In the example below, you should see also input values in your output.txt

printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);

Upvotes: 1

prog-fh
prog-fh

Reputation: 16920

You got the two values with scanf() but you didn't print them (with printf() for example), so they don't appear in stdout.

When we input something on the standard input with the keyboard, we can see the text just because the terminal (not your program) echoes these characters. So, redirecting your program's standard output does not change anything to that.

Upvotes: 1

Related Questions