[英]Why does not the input of a string work?
#include <stdio.h>
int main()
{
char temp[1024];
if(getchar() != 'y')
{
printf("no options\n");
return 1;
}
scanf(temp, "%s");
printf("%s", temp);
}
I get snippet as below. 我得到如下片段。 I just want twice input from user. 我只想从用户输入两次。 but the first input works, however the second directly skips and the printf("%s", temp);
但是第一个输入有效,但是第二个直接跳过,并且printf("%s", temp);
printed unexpected characters. 打印意外字符。 How can I resolve the problem.. thanx 我该如何解决问题.. thanx
The first parameter to scanf
is the format, and the second is the buffer. scanf
的第一个参数是格式,第二个参数是缓冲区。 You have it backwards. 你有倒退。 Try scanf( "%s", temp );
尝试scanf( "%s", temp );
. 。
Others have already given you the actual answer, and you should accept one of those but feel free to upvote me if you like this sage advice :-) 其他人已经给了您实际的答案,您应该接受其中的一个,但是如果您喜欢这个明智的建议,请随时赞成我:-)
Use of gets
should never be contemplated if you're looking for a robust application. 如果您正在寻找功能强大的应用程序,则永远不要考虑使用gets
。 That's because there's no way to guard against a buffer overflow which could render your program insecure. 那是因为没有办法防止可能导致程序不安全的缓冲区溢出。
I prefer a little function like getLine()
in the following program. 我喜欢以下程序中的getLine()
类的小功能。 It uses fgets
which can be protected from oveflow and is a robust solution. 它使用fgets
, 可以保护它们免受oveflow的侵害,并且是一种可靠的解决方案。
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
printf ("No input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long\n");
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
Sample runs with 'hello', CTRL D , and a string that's too big: 示例使用'hello', CTRL D和太大的字符串运行:
pax> ./qq
Enter string> hello
OK [hello]
pax> ./qq
Enter string>
No input
pax> ./qq
Enter string> dfgdfgjdjgdfhggh
Input too long
pax> _
You need to switch the parameters to scanf
. 您需要将参数切换为scanf
。
#include <cstdio>
using namespace std;
int main()
{
char buf[100];
while (true)
{
if (scanf("%s",buf) == EOF)
{
printf("fail");
return 1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.