Question:
how to display certain lines from a text file in C?
jnro
2014-03-28 03:52:44 UTC
i have a text file that contains song lyrics, but the program should only display the ones enclosed in "[" and "]".

text file:
Let it go, let it go
[Can’t hold it back anymore]
Let it go, let it go
Turn away and slam the door

output:
Can’t hold it back anymore


can anyone help me?
thanks in advance!
Four answers:
?
2014-03-28 04:46:17 UTC
Here is the program using the algorithm suggested by dewcoons:



#include



int main()

{

int flag;

char chr;



flag = 0;



chr = getchar();

while (chr != EOF)

{

if (chr == '[')

{

flag = 1;

}

else if (chr == ']')

{

flag = 0;

putchar('\n'); /* Just an extra newline */

}

else if (flag == 1)

{

putchar(chr);

}



chr = getchar();

}



return(0);

}





Just use the text file as the input of the program with a command like this: program.exe < lyrics.txt
?
2014-03-28 13:02:51 UTC
I don't know what files you want to process. So you could try the following. It accepts standard input, so you would need to "redirect" the file to the program using the < character on the command line and specifying the filename. The text between the [] must be 999 chars or less, though. Probably not a problem. But the program is "unsafe" if the number of chars is 1000 or more. Just so you know.



#include

char b[1000];

int main( void ) {

    char *z;

    int s= 1, c;

    while ( (c= fgetc( stdin )) != EOF ) {

        if ( c == '\n' ) s= 1;

        else if ( s == 1 && c == '[' ) z= b, s= 2;

        else if ( s == 2 && c == ']' ) *z= '\0', printf( "%s\n", b ), s= 0;

        else if ( s == 2 ) *z++= c;

        else if ( s != 0 ) s= 0;

    }

    return 0;

}
dewcoons
2014-03-28 04:01:29 UTC
algorithm



open the text file

set a variable as a flag to "no"

read one character at a time in a loop

if the flag is set to yes print the character - if the flag is set to no it will not print the character

if the character is a [, set the flag to yes - that turns on the printing

if the character is a ] set the flag to no - that turns off the printing

continue to read through the file unto you reach the end.
?
2014-03-28 08:32:28 UTC
use gets() or getline to read a line from the file

if the first letter is '[' then display the line ...

there ya go..


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...