从输入读取字符串空格字符? [英] Reading string from input with space character?

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

问题描述

我使用的是Ubuntu和我还使用Geany和codeBLOCK作为我的IDE。
我正在试图做的是阅读的字符串(如奥巴马),并把它放在一个变量:

I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE. What I'm trying to do is reading a string (like "Barack Obama") and put it in a variable:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    scanf("%s", name);
    printf("Your Name is: %s", name);

    return 0;
}

终端:

Enter your name: Barack Obama
Your Name is: Barack

我怎样才能使程序读取整个名称?

How can I make the program read the whole name?

推荐答案

使用:

fgets (name, 100, stdin);

100 是缓冲区的最大长度。你应该调整它根据自己的需要。

100 is the max length of the buffer. You should adjust it as per your need.

使用:

scanf ("%[^\n]%*c", name);

[] 是扫描集字符。 [^ \\ n] 讲述的是,虽然输入的的换行符(的'\\ n')取输入。然后用%* C 它读取输入缓冲区的换行符(未读),而 * 表示该读输入被丢弃(SUP分配pression),因为你不需要它了,这换行符在缓冲区不会为下次您可能需要输入任何问题。

The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the * indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.

在这里阅读有关扫描集和的分配燮pression 运营商。

Read here about the scanset and the assignment suppression operators.

请注意,你也可以使用获得但是......

Note you can also use gets but ....

不要使用获得()。因为它是不可能告诉不知道提前多少字符获取(数据)将读取,并且因为获得()将继续存储字符过去缓冲区末尾,这是非常危险的使用。它已被用于破坏计算机的安全性。使用与fgets()代替。

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

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

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