1
   #include<stdio.h>
   #include<conio.h>
   void sstring();
    int main()
    {
     char ch1[10],ch2;
     printf("Enter the value of first character : ");
     scanf("%s",&ch1);
     sstring(); 

     getch();
     return 0; 
    } 

    void sstring()
    {    char ch2;
         printf("Enter the value of second character : ");
         scanf("%c",&ch2);   

         printf("Got the second character"); 
    }

関数内の 2 番目の scanf が機能しない....プログラムは 2 番目の scanf で停止しませんか?

4

1 に答える 1

1

まず、2 番目の scanf が関数内にあるためではありません。

これは、最初の scanf (Enter を入力) からの 0xA (リターン) がまだ stdin バッファにあるためです。%s 引数は、入力時に最後の "\n" を読み取らないことに注意してください。後で scanf を呼び出す可能性に影響を与えないようにするには、文字列と行区切り文字の両方を常に読み取る必要があります。

char string[10], linedelim;
scanf("%s%c", string, &linedelim);

ここにあなたの例が再び来て、今働いています。

#include<stdio.h>
#include<conio.h>

void sstring();
int main()
{
 char ch1[10],ch2, linedelim;
 printf("Enter the value of first character : ");
 // read both the string and line delim
 scanf("%s%s",&ch1, &linedelim);
 sstring(); 
 getch();
 return 0; 
} 

void sstring()
{    char ch2;
     printf("Enter the value of second character : ");
     // read the second input
     scanf("%c",&ch2);   
     printf("Got the second character"); 
}

また、ユーザーが 10 文字を超える文字を入力すると、簡単にバッファ オーバーフローが発生する可能性があるため、この例は非常に壊れやすいことに注意してください。プログラムを簡単に破壊できる次のコマンド ラインを想像してみてください。

$ perl -e 'print "A" x 1000000' | ./a.out 

入力から文字列を読み取るために scanf() を使用するよりも良い方法は、入力のサイズを制御できる fgets() を使用することです。

于 2013-01-16T18:41:05.030 に答える