#include
#include
void sstring();
int main()
{
char ch1[10],ch2;
printf("Enter the value of first character : ");
scanf("%s",&ch1);
sstring();
getch();
trả về 0;
}
void sstring()
{ char ch2;
printf("Enter the value of second character : ");
scanf("%c",&ch2);
printf("Got the second character");
}
第二个 scanf 内部函数不起作用......程序不会在第二个 scanf 处停止?
首先,这并不是因为第二个 scanf 位于函数内部。
那是因为第一次 scanf(您输入 Enter)的 0xA(返回)仍然在标准输入缓冲区中。请注意,%s 参数不会读取输入中的最后一个“\n”。为了不影响以后可能对 scanf 的调用,您应该始终读取字符串和行分隔符。
char string[10], linedelim;
scanf("%s%c", string, &linedelim);
你的例子又来了,现在可以工作了。
#include
#include
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();
trả về 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(),因为您可以控制输入的大小。
Tôi là một lập trình viên xuất sắc, rất giỏi!