Reputation: 155
I am trying to implement a formatting feature into my code, first of all
I read a text file which was inputted by the user, and formatting features
such as ".br", ".sp" and ".ce" are contained inside this text file.
So I am trying to make an if statement that if the program finds the word ".br" it
should immediately break and start the next word on a new line, but I really
cannot think of way to do this.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = NULL;
char file_name[257] = {'\0'};
char line[61] = {'\0'};
char word[61] = {'\0'};
int out = 0;
printf ( "Enter file name:\n");
scanf ( " %256[^\n]", file_name);
if ( ( fp = fopen ( file_name, "r")) == NULL) {
printf ( "This file does not exist.\n");
return 1;
}
while ( ( fscanf ( fp, "%60s", word)) == 1) {
if ( strlen ( line) + strlen ( word) + 1 <= 60) {
strcat ( line, " ");
strcat ( line, word);
out = 0;
}
else {
printf ( "%s\n", line);
strcpy ( line, word);
out = 1;
}
if ((word) == ".br"){
}
}
if ( !out) {
printf ( "%s\n", line);
}
fclose ( fp);
return 0;
}
I created the IF statement for the ".br" feature but I really need help or some
clues what to actually put in the loop.
Upvotes: 0
Views: 68
Reputation: 16540
if( 0 == strcmp( word, ".br" ) )
{
printf( "%s", line );
printf( "\n" );
}
Note strings cannot be compared with ==
, must use something like strcmp()
the posted code needs a bit of rearranging so characters are not placed into line[]
until after checking if the token word[]
is NOT a format sequence.
Upvotes: 0
Reputation: 8286
Add an if condition to compare the word to ".br". Print out the current line and set line
to accept the next word in an empty string.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = NULL;
char file_name[257] = {'\0'};
char line[61] = {'\0'};
char word[61] = {'\0'};
int out = 0;
printf ( "Enter file name:\n");
scanf ( " %256[^\n]", file_name);
if ( ( fp = fopen ( file_name, "r")) == NULL) {
printf ( "could not open file\n");
return 1;
}
while ( ( fscanf ( fp, "%60s", word)) == 1) {
if ( strcmp ( word, ".br") == 0) {
printf ( "%s\n", line);
line[0] = '\0';
out = 1;
}
else if ( strlen ( line) + strlen ( word) + 1 < 60) {
strcat ( line, " ");
strcat ( line, word);
out = 0;
}
else {
printf ( "%s\n", line);
strcpy ( line, word);
out = 1;
}
}
if ( !out) {
printf ( "%s\n", line);
}
fclose ( fp);
return 0;
}
Upvotes: 1