對於以下代碼,我添加了兩個printf語句來測試兩個字符串是否被正確讀取。然而,當我輸入類似:abcabcabcza,CB 的輸出:使用getchar()讀取兩個字符串
abcabcabcza▒
CB9
有誰知道在哪裏符號在第一字符串的結尾,而「9」在第二個字符串的末尾,從哪裏來?非常感謝!
printf("\nEnter two words, seperated by a comma: ");
int temp1, temp2, index3, index4; char temp3[20], temp4[20];
index3=index4=0;
while((temp1 = getchar())!= ','){
temp3[index3++] = temp1;
}
printf("\n%s", temp3);
while((temp2 = getchar())!= '\n'){
temp4[index4++] = temp2;
}
printf("\n%s", temp4);
你需要在字符串末尾添加「\ 0」以便printf知道停止打印的位置。 temp3 []和temp4 []具有未定義的值。 – bestalign
你能詳細解釋一下嗎?我怎樣才能防止這一點? – Jobs
用0填充temp3 []和temp4 [] 0 – bestalign