2

「 Alan Turing 」と入力すると、「 Turing, A 」を出力するプログラムを書きたいと思います。しかし、私の次のプログラムでは、「uring, A」が出力されます。長い間考えましたが、Tの行先がわかりませんでした。コードは次のとおりです。

#include <stdio.h>
int main(void)
{
char initial, ch;

//This program allows extra spaces before the first name and between first name and second name, and after the second name.

printf("enter name: ");

while((initial = getchar()) == ' ')
    ;

while((ch = getchar()) != ' ')  //skip first name
    ;

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
while((ch = getchar()) != ' ' && ch != '\n')
{
    printf("%c", ch);
}
printf(", %c.\n", initial);

return 0;
}
4

3 に答える 3

3

あなたのバグはここにあります:

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
while((ch = getchar()) != ' ' && ch != '\n')
{
    printf("%c", ch);
}

最初のループは、スペース以外が見つかるまで文字を読み取ります。それがあなたの「T」です。次に、2 番目のループで次の文字 'u' で上書きし、出力します。2 番目のループを a に切り替えると、do {} while();機能するはずです。

于 2011-06-05T09:02:55.497 に答える
2
while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}

この部分は間違っています。そのifブロックは . の場合にのみ実行されるため、ch == ' '.

while ((ch = getchar()) == ' ');
printf("%c", ch);  //print the first letter of the last name

それを修正する必要があります。

char ではなくをgetchar返すことに注意してください。intある時点でファイルの終わりを確認したい場合、getcharの戻り値を に保存すると、バイトになりますchar

于 2011-06-05T09:02:42.400 に答える
0

getchar() を使用して標準入力から文字列を読み取るのは、あまり効率的ではありません。read() または scanf() を使用して入力をバッファに読み込み、文字列を操作する必要があります。それははるかに簡単になります。

とにかく、バグがある場所にコメントを追加しました。

while((ch = getchar()) != ' ')  //skip first name
    ;

// Your bug is here : you don't use the character which got you out of your first loop.

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
于 2011-06-05T09:05:46.680 に答える