![](/img/trans.png)
[英]Read arbitrary number of characters from stdin until pressing enter in C
[英]C read lines from stdin ending by pressing Enter
我正在用C編寫用於項目的程序,在這里我有這樣的輸入:
............xcx............
.........qeztodlea.........
.......ecnedivorpuzy.......
.....bqfjwxqindnrsatrs.....
....ucaamadisonoctoieax....
...ozkttqdxwltstaivcilex...
...ujknnakigzfasxninltxc...
..rabxaa...kohce...oelnyd..
..rithls...momrl...spayvh..
honolulu
oklahomacity
charleston
madison
montgomery
saltlakecity
springfield
第一組數據與第二組數據用空行分隔,我需要在一個Enter
上進行處理。
如果我將這些數據復制粘貼到終端窗口中,然后按Enter
,然后按Ctr + D(表示輸入結束),則可以正常工作,但是如果僅按Enter
,則仍然需要輸入數據。 我不知道要更改什么,所以僅在第一次Enter
完成輸入並繼續執行程序? 我知道這個問題聽起來很愚蠢,但是在我閱讀行的函數中我使用fgetc
,因為我需要檢查一些字母,如果要使用例如fgets
,它將在第一個nl
停止,要使用哪個函數? 也許我什么都沒得到,總的來說可能嗎?
我已經有了rLine函數來讀取行(使用fgetc):
char * rLine( int * length, int * ha ){
char *buff = malloc( LMAX ), *old = buff;
int count = 0, maxlen = LMAX, len = maxlen, c;
while ( (c = fgetc( stdin ) ) != '\n' ){
if ( c == EOF ) { *ha = R_EOF; break; }
if ( /* some conditions for c */ ) *ha = R_FALSE;
*buff ++ = c;
count++;
if ( -- len == 0 ){
len = maxlen;
buff = (char *)realloc( old, maxlen *= 2 );
old = buff;
buff += count;
}
}
*length = count;
*buff = '\0';
return old;
}
其中ha
某種錯誤消息處理的。 特納克斯
注意:好的,我發現輸入的結尾與CTRL + D
組合相同。 所以實際上檢查if ( c == EOF )
(或c == '\\0'
)對我來說還不錯。 因此,實際上,這個問題現在可以解決。
您是否熟悉'\\n'
換行和'\\r\\n'
換行?
添加此行並處理新的行情況:
if ( c == '\n' ) { // that is a new line }
您看過這篇文章嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.