只是想知道為什么我的函式 getline() 讀取最后一行兩次。
我應該從 tsv 檔案中讀取并將每一行列印到標準輸出。但不知何故繼續閱讀最后一行兩次。
char *line = NULL;
size_t line_buf_size = 0;
ssize_t line_size;
line_size = getline(&line, &line_buf_size, stdin);
int row = 0;
while (line_size >= 0)
{
row ;
line_size = getline(&line, &line_buf_size, stdin);
printf("%s", line);
如果檔案看起來像這樣
A B C
D E F
它列印
A B C
D E F
D E F
我如何解決它?
uj5u.com熱心網友回復:
你實際上跳過了第一行。
由于您是從 STDIN 讀取的,因此您鍵入的內容沒有檔案。你的輸出和輸入混淆了。我們可以通過更改您printf的添加前綴來看到這一點printf("output: %s", line);。
A B C <-- this is your input echoed to the screen
D E F <-- and this
output: D E F
output:
您的代碼正在讀取第一行,檢查它的長度,然后讀取下一行而不列印第一行。這就是為什么你錯過了第一行。
我們在最后得到了額外的空白列印,因為您正在檢查是否從前一行中讀取了任何內容。然后您無需檢查即可立即閱讀和列印。
// Read the first line.
line_size = getline(&line, &line_buf_size, stdin);
int row = 0;
// Check if you read anything from the *previous* line.
while (line_size >= 0)
{
row ;
// Read the next line overwriting the first line.
line_size = getline(&line, &line_buf_size, stdin);
// Print the second and subsequent lines without first checking
// if you read anything.
printf("%s", line);
}
相反,閱讀、檢查和列印。
#include <stdio.h>
int main() {
char *line = NULL;
size_t line_buf_size = 0;
int row = 0;
// Read and check.
while (getline(&line, &line_buf_size, stdin) > -1)
{
row ;
// Print.
printf("output: %s", line);
}
}
我們得到交錯的輸入和輸出。
A B C
output: A B C
D E F
output: D E F
您不需要存盤行長度,但如果您在比較之前確實在分配周圍放置了括號。這確保(line_size = getline(...)) > -1沒有line_size = (getline(...) > -1)。那就是將 getline 的回傳值存盤在 line_size 中,然后檢查它是否為 -1。不檢查 getline 是否回傳 -1 并將真/假結果存盤到 line_size。
while((line_size = getline(&line, &line_buf_size, stdin)) > -1)
uj5u.com熱心網友回復:
說getline回傳 -1 表示 EOF。下一步你要怎么做?你列印。哎呀!
char *line = NULL;
size_t line_buf_size = 0;
int row = 0;
while ( getline(&line, &line_buf_size, stdin) >= 0 ) {
row;
printf("%s", line);
}
if (ferror(stdin)) {
perror("getline");
exit(1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322583.html
上一篇:如何修復C編程中的分段錯誤?
