我正在嘗試撰寫一個獲取一個或多個輸入行的程式,如果一行太長,它會以最大數量的字符折疊。我的方法是將輸入字符寫入給定長度的第一個陣列中。如果達到最大長度或'\n'作為輸入,我將內容復制到一個更大的陣列中,這將是要列印的最終字串并獲取輸入中的第二行。問題是:它不起作用,我不知道為什么。謝謝您的幫助
#include <stdio.h>
#define MAXCOL 10
#define FINAL_LENGTH 300
char line[MAXCOL];
char final_string[FINAL_LENGTH];
extern int fnlstr_pos = 0;
int main()
{
int pos, c;
pos = 0;
while(c=getchar() != EOF)
{
line[pos] = c;
if (pos 1 >= MAXCOL || c == '\n'){
to_printandi(pos);
pos = 0;
}
pos;
}
printf("%s", final_string);
}
to_printandi(pos)
int pos;
{
int i;
for(i = 0; i <= pos; i){
final_string[fnlstr_pos] = line[i];
fnlstr_pos;
}
if (final_string[fnlstr_pos] != '\n'){
final_string[ fnlstr_pos] = '\n';
}
fnlstr_pos;
}
uj5u.com熱心網友回復:
代碼中有幾個問題。其他人已經指出了該getchar()行中的錯誤。
更多的變數、更多的函式和更多的代碼只會一團糟。如果你花一些時間思考你想要達到的目標,慢慢來,你可以用更少的努力得到你的結果。更少的代碼充滿有用的注釋,使程式更好。
編輯
用新的眼光看代碼,我意識到將'尾隨'位元組顯式設定為'\ 0'的兩行在已經初始化為0的位元組之上寫入了0。已將這兩行注釋掉,因為它們是多余的。
#include <stdio.h>
int main () {
char buf[ 1024 ] = { 0 }; // buffer initialised
int ch, cnt = 0, ccnt = 0; // input char and counters
while( ( ch = getchar() ) != EOF ) { // get a character
ccnt ; // count this character
buf[ cnt ] = (char)ch; // assign this character
// buf[ cnt ] = '\0'; // string always terminated
if( buf[ cnt-1 ] == '\n' ) // user supplied LF?
ccnt = 0; // reset the counter (for width)
else
if( ccnt == 10 ) { // reached max output width?
buf[ cnt ] = '\n'; // inject a LF
// buf[ cnt ] = '\0'; // string always terminated
ccnt = 0; // reset the counter (for width)
}
}
puts( buf ); // output the whole shebang
return 0;
}
0123456789abcdefghijklmnop
qrs
tuv
wxyz
^D // end of input
0123456789
abcdefghij
klmnop
qrs
tuv
wxyz
與 OP 代碼一樣,這不會測驗是否超出緩沖區。一個簡單的補充留給讀者作為練習。
EDIT2:
再說一遍,為什么要溢位緩沖區?
#include <stdio.h>
void main( void ) {
for( int ch, n = 0; ( ch = getchar() ) != EOF; /**/ )
if( (n = putchar( ch ) == '\n' ? 0 : n 1) == 10 )
putchar( '\n' ), n = 0;
}
uj5u.com熱心網友回復:
這個問題非常廣泛,如果您說出問題所在,這將很有幫助,但我可以看到一個問題——您不會終止 final_string 變數。添加
final_string[fnlstr_pos] = '\0';
在 printf 之前。
也許這可以解決您遇到的問題。
uj5u.com熱心網友回復:
對于初學者來說,這個宣告
while(c=getchar() != EOF)
相當于
while( c = ( getchar() != EOF ) )
所以如果沒有遇到 EOF,c 總是等于 1。
你需要寫
while( ( c=getchar() ) != EOF)
并且您需要在輸入序列中附加終止零字符 '\0' tp 形成一個字串。
另一個問題是這些帶有 for 回圈的代碼片段
for(i = 0; i <= pos; i){
final_string[fnlstr_pos] = line[i];
fnlstr_pos;
}
在回圈中,變數fnlstr_pos增加了,然后這個 if 陳述句
if (final_string[fnlstr_pos] != '\n'){
final_string[ fnlstr_pos] = '\n';
}
呼叫未定義的行為,因為變數指向陣列的未初始化元素。
uj5u.com熱心網友回復:
主要問題在這里:
while(c=getchar() != EOF)
給定運算子優先級,這將導致相同的結果:
while(c= (getchar() != EOF))
回圈內也是(真c)。1
將其更改為:
while((c=getchar()) != EOF)
這是主要問題。正如@Hogan 建議的那樣,還有其他問題,例如非空終止字串。當您將它們宣告為全域時,它們將被清零,因此您可以擺脫這種情況,盡管在用戶提供具有最大長度的字串的情況下并非如此。
<string.h>此外,如果您可以使用字串操作函式而不是逐位元組復制,那么它將大大改進代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512686.html
上一篇:C If、elseif和else陳述句根據用戶的答案產生不正確的答案
下一篇:將資料發送到服務陣列蠻力
