第二次扫描内部函数不工作…程序不停止在第二次扫描


   #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"); 
    }

第二个scanf inside函数不工作....程序在第二次扫描时没有停止

首先,这并不是因为第二个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(),因为您可以控制输入的大小。

最新更新