scanf()不接受空格 [英] scanf() doesn't accept whitespace

查看:107
本文介绍了scanf()不接受空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要scanf()调用来接受空格(没有制表符或换行符,只需''空间字形).

I need a scanf() call to accept whitespace (no tabs or newlines, just ' ' space glyphs).

char buffer[2048];
scanf(" %2048[0-9a-zA-Z ]s", buffer);

我从这个问题的答案中得到了这种格式说明符:

This format specifier I got from the answer to this question:

how-do-you-allow-spaces进入使用scanf

虽然可以很好地接受第一个输入序列,但是它会在第一个空白字符所在的地方终止,并带有一个空字符.这是怎么回事?我也许使用了错误的格式?

While it accepts the first sequence of input just fine, it terminates where the first whitespace character is, with a null character. What's going on? Am I perhaps using the wrong format?

我应该说,我在这里使用scanf()是因为安全不是问题;我是唯一会使用此特定程序的人,并且输入格式严格.

I should say, I'm using scanf() here because safety isn't a concern; I'm the only person who'll ever use this particular program, and the input is rigidly formatted.

推荐答案

使用 scanf(%[^ \ n]",buffer); .它将接受空白.

示例程序-

int main()
{
    char buffer[2048];
    printf("Enter the string\n");
    scanf("%[^\n]",buffer);

    printf("%s\n", buffer);
    return 0;
}

输出-

root@sathish1:~/My Docs/Programs# ./a.out 
Enter the string
abc def ghi ijk
abc def ghi ijk
root@sathish1:~/My Docs/Programs# 

这篇关于scanf()不接受空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆