Where did I go wrong? I\'ve written the code but can\'t get it to \"print the ou
ID: 3536319 • Letter: W
Question
Where did I go wrong? I've written the code but can't get it to "print the output to screen"
Here's the assignment:
Have a program prompt the user for a filename to open. Change every alphabetic character in the file to a capital letter. Numbers and special characters should not be changed. Print the output to the screen.
Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char line[81], filename[21];
int i;
FILE *inFile;
printf(" Please enter the name of a file: ");
gets(filename);
inFile = fopen(filename, "r+");//r+ mode used to modify the content of file
if (inFile == NULL)
{
printf(" The file %s was not successfully opened.", filename);
printf(" Please check that the specified file exists.");
exit(1);
}
while (fgets(line, 81, inFile) != NULL)
{
printf(" %s", line);
for(i = 0; line[i]; ++i){
if(line[i]>='a'&& line[i]<='z')
{
char mychar=line[i];
putchar (toupper(mychar));
}
}
fputs(line,inFile);
fclose(inFile);
return 0;
}
}
Explanation / Answer
This can be modified in to
/* readFile.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* don't use conio.h and getch to keep code portable */
#define BUFLEN 128
int main()
{
char line[ BUFLEN ],
filename[ BUFLEN ],
c,
*p;
int chars = 0, letters = 0, lines = 0;
FILE* inFile;
printf( "Please enter the name of a file: " );
fflush( stdout );
fgets( filename, 128, stdin ); /* *avoid* using gets ... */
p = strchr( filename, ' ' );
if( p ) * p = ''; /* strip off ' ' if there ...*/
else while( getchar() != ' ' ) ; /* else flush rest of char's in stdin */
inFile = fopen( filename, "r" );
if( inFile )
{
while( fgets( line, BUFLEN, inFile ) )
{
++lines;
printf( "%s", line ); /* leavinng ' ' on ends of file lines ...*/
}
rewind( inFile );
printf( " File contents with line numbered: " );
while( ( c = fgetc( inFile )) != EOF )
{
++chars;
if( isalpha( c ) )
{
printf( " %d : ", chars );
++letters;
putchar(c );
}
}
fclose( inFile );
}
else
{
printf( " The file %s was not successfully opened.", filename );
printf( " Please make sure the specified file exists. " );
}
printf( " lines = %d, chars = %d, letters = %d ", lines, chars, letters );
printf( "Press 'Enter' to continue/exit ... " );
fflush( stdout );
getchar();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.