Home>

Currently, I am writing code that inputs multiple strings from the file input.txt by pipeline and sorts the strings in lexicographic order.
The correct inputs and outputs are as follows.

[Input] (input.txt)
cat
bench bench
dog
apple
e-mail

【output】
before:
cat
bench bench
dog
apple
e-mail

after:
apple
bench bench
cat
dog
e-mail (no line break only at the end)

Sorting succeeds with my code, but the output format (line feed) does not work this way.
I would appreciate it if you could tell me the reason and how to fix it.

Corresponding source code
#include<stdio.h>
#include<string.h>
void strSort (int size, char str [30] [31]) {
    char tmp [31];
    for (int i = 0;i<size-1;i ++) {
        for (int j = i + 1;j<size;j ++) {
            if (strcmp (str [i], str [j])>0) {
                strcpy (tmp, str [i]);
                strcpy (str [i], str [j]);
                strcpy (str [j], tmp);
            }
        }
    }
}
void strlist (int size, char str [30] [31]) {
    for (int i = 0;i<size;i ++) {
        printf ("% s", str [i]);
        if (i! = size) printf ("\ n");
    }
}
int main () {
    int i, size;
    char str [30] [31];
    for (i = 0;i<30;i ++) {
        if (scanf ("% s", str [i]) == EOF) {
            size = i + 1;
            break;
        }
    }
    printf ("before: \ n");
    strlist (size, str);
    printf ("\ n");
    strSort (size, str);
    printf ("after: \ n");
    strlist (size, str);
    return 0;
}
Console screen (VS Code)
Get-Content input.txt |. \ A.exe
before:
cat
bench bench
dog
apple
e-mail
after:
     (← There is no line break here)
apple
bench bench
cat
dog
e-mail
Supplementary information (FW/tool version, etc.)

Execution environment: VSCode
Compile with gcc.

c
  • Answer # 1

    strlistIn the loop in the definition of, the continuation condition of this loop isiis.iButsizeBecause it only repeats for a smaller period of time.i == sizeIt cannot be. That is alwaysi! = sizeIs true.

    If you decide not to add a line break at the end of the loopifThe sentence isif (iIt is necessary to write something like this.

  • Answer # 2

    I think this is because EOF is included in size.
    The size may be as follows.

    if (scanf ("% s", str [i]) == EOF) {
       size = i;// +1 is not necessary
       break;