0

So I have this code:

void read_string(char *dest, int size) {
    fgets(dest, size, stdin);
    unsigned int i;
    for(i=0; i<strlen(dest); i++)
        if(dest[i]=='\n')
            dest[i]='\0';
}

int main() {
    char arr[1000][64];
    int i=0;
    while(i<1000) {
        printf("Enter filename: ");
        read_string(arr[i], 62);
        if(strlen(arr[i])==0)
            break;
        i++;
    }
}

However, if I copy a string such as:

a


(excluding this line)

...and paste it into the command prompt, the output is as follows:

Enter filename: a

Enter filename:

The loop breaks and the program goes on. My desired outcome in that situation would be for the program to break the loop without displaying the next "Enter filename" message. However, if the user ends their input with a single linefeed, the loop should simply continue.

I'm aware why it doesn't work like intended in that form, but I'm out of ideas at this point. Whatever I try to do, it still works the same.

In case you're wondering why I want it to work in such a weird way, this is a part of my homework assignment, completely unrelated to the main purpose of the exercise. However, my program is failing a unit test because of this.

Alan
  • 23
  • 4
  • Is testing copy-pasted input part of your test case? – R Sahu Apr 20 '18 at 17:59
  • `fgets` can't get a double-newline: it stops at the first newline or at size limit. Here is an easy way to [Remove trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Apr 20 '18 at 18:03
  • Oh, I think I see: the remaining input is presented to the next loop. So you could filter unsatisfactory input (such as a single newline) and skip to the next loop – just as you would if the user only presses "Enter". – Weather Vane Apr 20 '18 at 18:09
  • 1
    It seems like you are looking for a magic way to distinguish between a pasted newline character and a typed by hand newline character. There isn't any. – n. m. could be an AI Apr 20 '18 at 18:31

0 Answers0