GaryB
GaryB

Reputation: 51

Make fgets() ignore a new line

The following code should take strings from the user (containing data of items in a storage).

I'm having trouble make the program iterate over to a new line. It aborts when I push "enter" but instead I need it to just take the next line as input. code:

for (i; i < STORE_SIZE; i++) {
    fgets(seq, MAX_STRING_LEN, stdin);
    if (strcmp(seq, "stop")) {
        break;
    }
    else {
        init(seq, ptr);
        *(storage + i) = ptr;
    }
}

The program should abort when it gets the string "stop" in the next line, and not by pushing enter.

Upvotes: 4

Views: 12175

Answers (1)

dreamlax
dreamlax

Reputation: 95315

fgets will always add the linefeed character to the buffer when it encounters it. The only way to get rid of it is to manually remove it, e.g.:

size_t len = strlen(seq);
if (len > 0 && seq[len - 1] == '\n')
    seq[len - 1] = '\0';

Or, more concisely but perhaps more confusingly:

seq[strcspn(seq, "\n")] = '\0';

The strcspn() function looks for the first occurrence of any of the characters in the second argument inside the first argument, and returns the index of that character, or the index of the end of the string if none of the characters were found.

Also, keep in mind that strcmp() returns 0 if the strings are equal. The function is used to compare strings lexically.

Additionally, the first part of your for loop is meaningless, are you sure you didn't mean:

for (i = 0; ...)

Upvotes: 6

Related Questions