我正在用 C 編程語言做練習,你需要在其中創建一個函式來反轉一行。所以我做到了,它有時會起作用。但只有幾次。使用相同的測驗它會給出不同的結果。我真的不明白,希望能得到一些幫助。4 次嘗試 3 次,它會列印大約 150 個空格,4 次中的 1 次會像我想要的那樣列印反轉的行,盡管由于某種原因最終會出現一些垃圾。我正在考慮用指標來做這件事,但現在還想不通。這是我的代碼:
#include <stdio.h>
void reverse(char theline[150]){
int i, j;
char tmp[150];
for (i = 0; theline[i] != 0; i ){
tmp[i] = theline[i];
}
for (j = 0; i >= 0; j ){
theline[j] = tmp[i];
i--;
}
}
int main() {
char line[150];
char c;
int counter = 0;
do {
counter = 0;
while (((c = getchar()) != '\n') && (c != EOF)) { //one line loop
line[counter] = c;
counter ;
}
if (counter > 80){
reverse(line);
printf("%s\n", line);
}
}
while (c != EOF);
return 0;
}
我用“gcc -g -Wall program -o test”編譯它,編譯器沒有給我任何錯誤或警告。我的作業系統是 Ubuntu,我用“./test < longtext.txt”對其進行了測驗。這個文本檔案有幾行不同的長度。
uj5u.com熱心網友回復:
在這個回圈之后
while (((c = getchar()) != '\n') && (c != EOF)) { //one line loop
line[counter] = c;
counter ;
}
字符陣列行不包含字串,因為存盤的字符沒有附加終止零字符'\0'。
所以函式內的這個回圈
for (i = 0; theline[i] != 0; i ){
tmp[i] = theline[i];
}
呼叫未定義的行為。
您需要在陣列后面附加終止零字符'\0'。
但是即使傳遞的字符陣列將包含一個字串,第二個 for 回圈
for (i = 0; theline[i] != 0; i ){
tmp[i] = theline[i];
}
for (j = 0; i >= 0; j ){
theline[j] = tmp[i];
i--;
}
如果陣列 . 則將終止零字符 '\0' 寫入第一個位置theline。結果,您將得到一個空字串。
此外,該函式不得使用幻數 150 和輔助陣列。
請注意,變數c應宣告為具有 type int。通常,型別char可以表現為型別signed char或unsigned char取決于編譯器選項。如果它將表現為型別,unsigned char則此條件
c != EOF
將始終評估為真。
在不使用標準 C 字串函式的情況下,可以通過以下方式宣告和定義函式
char * reverse( char theline[] )
{
size_t i = 0;
while ( theline[i] != '\0' ) i ;
size_t j = 0;
while ( j < i )
{
char c = theline[j];
theline[j ] = theline[--i];
theline[i] = c;
}
return theline;
}
這是一個演示程式
#include <stdio.h>
char * reverse( char theline[] )
{
size_t i = 0;
while ( theline[i] != '\0' ) i ;
size_t j = 0;
while ( j < i )
{
char c = theline[j];
theline[j ] = theline[--i];
theline[i] = c;
}
return theline;
}
int main( void )
{
char s[] = "Hello World!";
puts( s );
puts( reverse( s ) );
}
程式輸出為
Hello World!
!dlroW olleH
uj5u.com熱心網友回復:
當您可以在輸入的字符到達時簡單地存盤它們時,為什么還要顛倒緩沖區。
#include <stdio.h>
int main() {
for( ;; ) {
char line[ 150 ];
int c, counter = sizeof line;
line[ --counter ] = '\0';
// NB: EOF is an int, not a char
while( ( c = getchar() ) != '\n' && c != EOF && counter > 0 )
line[ --counter ] = (char)c;
printf( "%s\n\n", line counter );
counter = sizeof line;
}
return 0;
}
輸出:
the quick
kciuq eht
Once upon a time in a land far awy
ywa raf dnal a ni emit a nopu ecnO
I wish I was what I was when I wished I was what I am now.
.won ma I tahw saw I dehsiw I nehw saw I tahw saw I hsiw I
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504636.html
上一篇:計算R中許多資料幀的sd和均值
