My instructions: Write a program that repeatedly (until end-of-file) reads in a character
from the input stream. If the character is upper case, change it to lower case
and write it to the output stream. For all other characters, write the
character unchanged to the output stream.
Use getchar() for input, Use putchar() for output, and use input redirection
for connecting the input file to the program
My project name is Input and my textfile is input.txt. When I run it I type “Input < input.txt” The program just mimics that on the command window though so how do I get it to read from the text file?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char c, x;
c=getchar();
while (c != EOF)
{
c=getchar();
x = tolower(c);
if (isupper(c))
{
putchar(x);
}
else
{
putchar(c);
}
}
system("Pause");
}
I believe the problem is that you do not want to go to the program and type in
Input < input.txt. Instead, you want to open a terminal program, change directory into the directory containing the project, and then run the program from the command line by writingInput < input.txt. This starts up the program and uses the contents ofinput.txtas the standard input stream, rather than reading text from the console.That said, there are two bugs in your code. First, note that you have the line
outside of your loop that does the input reading. You then immediately call
again inside the loop. This means that you are discarding the very first character that you read in.
Second, your loop runs one more time than it needs to. If the second call to
getchar()returnsEOF, you do not detect this until after the current loop iteration finishes. This is because your check forEOFis at the top of the loop, which isn’t reached until after you’ve already printed out theEOFcharacter. To fix this, consider using the loop-and-a-half idiom and breaking out of the loop in the middle:Stylistically, are you sure that you need both the
ifandelsebranches here? Recall thattolowerwill not change the values of characters that aren’t upper-case, so having one case for upper-case letters and one for lower-case is redundant. You can just output the character produced bytolowerwithout the special cases.Hope this helps!