我應該閱讀從「A」到「Z」命名的一些變量,然後評估他們的空行。變量中的值是矩陣。這是示例輸入:查找使用的fscanf
B=[5 2 4; 0 2 -1; 3 -5 -4]
E=[-6 -5 -8; -1 -1 -10; 10 0 -7]
R=[-1 -7 6; -2 9 -4; 6 -10 2]
R+E+B
我寫了一個算法,可以正確讀取所有變量。但是我無法檢測到空行。我寫了這個:
// FILE* input = stdin;
while(true) {
char name = '#';
// Reads the matrix, returns null on error
Matrix* A = matrix_read_prp_2(input, &name);
if(A==NULL) {
// throw error or something
}
// Print the matrix
matrix_print_prp_2(A, stdout);
// consume one new line
char next;
if(fscanf(input, "\n%c", &next)!=1)
// Program returns error here
if(next=='\n')
break;
// if not new line, put the char back
// and continue
ungetc(next, input);
}
我認爲對空行,fscanf(input, "\n%c", &next)
會讀'\n'
到next
,但它實際上跳過第二線並讀取R
。
我如何檢查是否下一行是空的流用C?
這是非常,非常難以察覺任何形式的換行用'的scanf()'和朋友。如果你需要檢測空行,那麼使用'fgets()'或者等價的方法來讀取資料,'sscanf()'在你知道它不是空的之後分析這些行。 'scanf()'格式字符串中的任何空格都與零個或多個空格字符序列匹配;換行符,空格,製表符都是空格。 '「\ n%c」'中的換行符跳過空白字符,直到下一個字符不是空格。 –