PS: those who did not read and did not understand my answer carefully, please respect yourself, DO NOT VOTE FOR BE!
Besides "get the whole line and then use sscanf", read char on char until "\ n" is entered, also the best way. If a program encounters an "h" or "q", it can immediately take the appropriate action, and you will also provide real-time analysis of the input stream for the clouds.
Example:
#define ROW_IDX 0 #define COL_IDX 1 int c; int buffer[2] = {0,0}; int buff_pos; while( (c = getchar())) { if (c == '\n') { //a line was finished /* row = buffer[ROW_IDX]; col = buffer[COL_IDX]; */ buff_pos = 0; memset(buffer , 0 , sizeof(buffer));//clear the buffer after do sth... } else if (c == 'h') { //help } else if (c == 'q') { //quit } else { //assume the input is valid number, u'd better verify whether input is between '0' and '9' if (c == ' ') { //meet whitespace, switch the buffer from 'row' to 'col' ++buff_pos; } else { buffer[buff_pos%2] *= 10; buffer[buff_pos%2] += c - '0'; } } }
source share