Pad [Enter] number is not \ n in C?

I am working on a small C program for a college assignment, and I noticed a strange error in my code. I use an iMac with a short keyboard, but its battery was flat, so I plugged in a standard USB keyboard with a numeric keypad.

It’s strange that if I press [Enter] on my numeric keypad, it seems to do what the regular [Enter] key does, but \ n I try to detect in the stdin function that I did to read the keyboard input, it does not work when I am using the numeric keypad [Enter].

Wtf?

Here is my function that reads user input:

/* This is my implementation of a stdin "scanner" function which reads * on a per character basis until the the termination signals are found * and indescriminately discarding all characters in the input in excess * of the supplied (limit) parameter. Eliminates the problem of 'left-over' * characters 'polluting' future stdin reads. */ int readStdin(int limit, char *buffer) { char c; int i = 0; int read = FALSE; while ((c = myfgetc(stdin)) != '\n' && c != '\0') { /* if the input string buffer has already reached it maximum limit, then abandon any other excess characters. */ if (i <= limit) { *(buffer + i) = c; i++; read = TRUE; } } /* clear the remaining elements of the input buffer with a null character. */ for (i = i; i < strlen(buffer); i++) { *(buffer + i) = '\0'; } return read; } /* This function used to wrap the standard fgetc so that I can inject programmable * values into the stream to test my readStdin functions. */ int myfgetc (FILE *fin) { if (fakeStdIn == NULL || *fakeStdIn == '\0') return fgetc (fin); return *fakeStdIn++; } 

NB: myfgetc and the following *fakeStdIn are part of the way I can unit test my code and "inject" elements into the stdin stream programmatically, as someone suggested on this question: How to write a test function for another function using stdin input? .

+4
source share
3 answers

So it turns out that this is Mac OSX. I spoke with other Mac users and they have the same problem. I never found a fix because it simply does not exist. The problem does not occur on Solaris machines, and since it is the OS on which the code will run, I think it does not really matter.

I myself will answer this question with the answer that its only one of these OSX "quirks" and will be done with it.

0
source

What result do you get for this tiny test?

 #include <stdio.h> int main(int argc, char* argv[]) { int c; while((c=getchar()) != EOF) { printf("%d\n", c); } return 0; } 
+1
source

It is possible that on a Mac you get \r\n , not just \n .

0
source

All Articles