读取字符串使用scanf函数空间? [英] Reading string with spaces using scanf?

查看:97
本文介绍了读取字符串使用scanf函数空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以下,要求输入,然后取一个字符串(用空格),然后再去做。但它反复第一个字符串中键入后输出的输入$。

 字符命令[80];而(1)
    {
        的printf(输入$);
        scanf函数(%[^ \\ n],命令);
    }

我的输出: NPUT $输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$输入$ $输入$输入$输入$输入$输入$输入$输入$输入$输入$输入^ C

我要什么:

 输入$喜
输入$这可能需要空间
输入$


解决方案

您通常要使用的是这样的:

 字符命令[80];而(1)
{
    的printf(输入$);
    scanf函数(%79 [^ \\ n]的%* C,命令);
}

在'79'prevents缓冲区溢出,而%* C 消耗从输入缓冲区的新线。它有一个小缺点:它仍然会消耗(和扔掉)字符,即使在输入缓冲区中的下一个字符的的新线。如果你有对付这种可能性,你可以读它,忽略它,除非你的命令缓冲区已满:

 烧焦忽略;scanf函数(%79 [^ \\ n]%C,命令和放大器;忽略);如果(strlen的(命令)== 79)
    //`ignore`可能不应该毕竟忽略

I want the following to ask for input and then take in a string (with spaces), then do it again. But it repeatedly outputs "input$" after typing in the first string.

char command[80];

while(1)
    {
        printf("input$ ");
        scanf("%[^\n]", command);    
    }

My output: nput$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$^C

What I want:

input$ hi
input$ this can take spaces
input$

解决方案

You normally want to use something like:

char command[80];

while(1)
{
    printf("input$ ");
    scanf("%79[^\n]%*c", command);
}

The '79' prevents a buffer overflow, and the %*c consumes the new-line from the input buffer. It has one minor shortcoming: it will still consume (and throw away) a character, even if the next character in the input buffer is not a new-line. If you have to deal with that possibility, you can read it and ignore it unless your command buffer is full:

char ignore;

scanf("%79[^\n]%c", command, &ignore);

if (strlen(command) == 79)
    // `ignore` probably shouldn't be ignored after all

这篇关于读取字符串使用scanf函数空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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