0

I'm trying to output a series of lines using a printf statement within nested for loops. The properly formatted output should have the very last argument of the printf statement, which is just a number in brackets at the end of each line, stay on that same line, but in my case, the number always goes to the next line. Here's my code:

for(i = 0; i < wordCount_keyword; i++) {
        for(j = 0; j <= lineCount; j++) {
            if(strstr(inputLines[j], keywords[i]) != NULL) {
                printf("%-20s %s (%d)\n", keywords_upper[i], inputLines[j], j+1);
            }
        }
    }

Here's the output I'm getting:

CAT                  the fish a dog cat dog rabbit
 (1)
CAT                  the fish and cat 
 (2)
DOG                  the fish a dog cat dog rabbit
 (1)
ELEPHANT             a rabbit or elephant
 (3)
FISH                 the fish a dog cat dog rabbit
 (1)
FISH                 the fish and cat 
 (2)
RABBIT               the fish a dog cat dog rabbit
 (1)
RABBIT               a rabbit or elephant
 (3)

Here's the correct output that I should be getting:

CAT       the fish a dog cat dog rabbit (1)
CAT       the fish and cat  (2)
DOG       the fish a dog cat dog rabbit (1*)
ELEPHANT  a rabbit or elephant (3)
FISH      the fish a dog cat dog rabbit (1)
FISH      the fish and cat  (2)
RABBIT    the fish a dog cat dog rabbit (1)
RABBIT    a rabbit or elephant (3)

What am I doing wrong?

Johnny Sack
  • 69
  • 2
  • 12
  • Your string probably contains the linefeed – Simson Feb 14 '20 at 06:56
  • It looks like your inputLines have newlines in them. – robthebloke Feb 14 '20 at 06:56
  • 3
    It looks like each `inputline[]` has a newline (`\n`). Q: Are you reading inputlines with `fgets()`? If so, did you remember to strip the trailing newline? Look here: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – FoggyDay Feb 14 '20 at 06:56
  • Perhaps `inputLines[j]` contains a trailing newline? If you have read those "lines" with [`fgets`](https://en.cppreference.com/w/c/io/fgets) they *will* have a trailing newline (if it fits). – Some programmer dude Feb 14 '20 at 06:56
  • @FoggyDay Yes I'm reading input lines with fgets(). What can I do about this? – Johnny Sack Feb 14 '20 at 06:57
  • @JohnnySack You should read you string before printing and remove any trailing new line character if any and then print the string – Sharad Gaur Feb 14 '20 at 06:58
  • @FoggyDay Yes that approach worked! Thanks!!!! – Johnny Sack Feb 14 '20 at 07:03

0 Answers0