C语言 如何使用C从键盘读取字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7709452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:52:05  来源:igfitidea点击:

How to read string from keyboard using C?

cstringscanf

提问by mainajaved

I want to read a string entered by the user. I don't know the length of the string. As there are no strings in C I declared a pointer:

我想读取用户输入的字符串。我不知道字符串的长度。由于 CI 中没有字符串声明为指针:

char * word;

and used scanfto read input from the keyboard:

并用于scanf从键盘读取输入:

scanf("%s" , word) ;

but I got a segmentation fault.

但我遇到了分段错误。

How can I read input from the keyboard in C when the length is unknown ?

当长度未知时,如何从 C 中的键盘读取输入?

回答by Paul R

You have no storage allocated for word- it's just a dangling pointer.

您没有分配存储空间word- 它只是一个悬空指针

Change:

改变:

char * word;

to:

到:

char word[256];

Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.

请注意,此处 256 是一个任意选择 - 此缓冲区的大小需要大于您可能遇到的最大可能字符串。

Note also that fgetsis a better (safer) option then scanffor reading arbitrary length strings, in that it takes a sizeargument, which in turn helps to prevent buffer overflows:

还要注意,fgets是比scanf更好(更安全)的选项,用于读取任意长度的字符串,因为它需要一个size参数,这反过来有助于防止缓冲区溢出:

 fgets(word, sizeof(word), stdin);

回答by glglgl

I cannot see why there is a recommendation to use scanf()here. scanf()is safe only if you add restriction parameters to the format string - such as %64sor so.

我不明白为什么建议在scanf()这里使用。scanf()仅当您向格式字符串添加限制参数时才是安全的 - 例如%64s左右。

A much better way is to use char * fgets ( char * str, int num, FILE * stream );.

更好的方法是使用char * fgets ( char * str, int num, FILE * stream );.

int main()
{
    char data[64];
    if (fgets(data, sizeof data, stdin)) {
        // input has worked, do something with data
    }
}

(untested)

(未经测试)

回答by David C. Rankin

When reading input from any file (stdin included) where you do not know the length, it is often better to use getlinerather than scanfor fgetsbecause getlinewill handle memory allocation for your string automatically so long as you provide a null pointer to receive the string entered. This example will illustrate:

当从任意文件(标准输入含税),你不知道长读输入,通常最好使用是getline不是scanf还是fgets因为getline会处理内存分配您的字符串自动,只要你提供一个空指针接收输入的字符串。这个例子将说明:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");
    }

    free (line);  /* free memory allocated by getline */

    return 0;
}

The relevant parts being:

相关部分是:

char *line = NULL;  /* forces getline to allocate with malloc */
size_t len = 0;     /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);

Setting lineto NULLcauses getline to allocate memory automatically. Example output:

设置lineNULL使 getline 自动分配内存。示例输出:

$ ./getline_example

Enter string below [ctrl + d] to quit
A short string to test getline!

  read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL

  read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

So with getlineyou do not need to guess how long your user's string will be.

因此,getline您无需猜测用户的字符串有多长。

回答by Ananth Reddy

#include<stdio.h>

int main()
{
    char str[100];
    scanf("%[^\n]s",str);
    printf("%s",str);
    return 0;
}

input: read the string
ouput: print the string

输入:读取字符串
输出:打印字符串

This code prints the string with gaps as shown above.

此代码打印带有间隙的字符串,如上所示。

回答by Juho

You need to have the pointer to point somewhere to use it.

您需要让指针指向某个地方才能使用它。

Try this code:

试试这个代码:

char word[64];
scanf("%s", word);

This creates a character array of lenth 64 and reads input to it. Note that if the input is longer than 64 bytes the word array overflows and your program becomes unreliable.

这将创建一个长度为 64 的字符数组并读取它的输入。请注意,如果输入长度超过 64 字节,则字数组会溢出并且您的程序变得不可靠。

As Jens pointed out, it would be better to not use scanf for reading strings. This would be safe solution.

正如 Jens 所指出的,最好不要使用 scanf 来读取字符串。这将是安全的解决方案。

char word[64]
fgets(word, 63, stdin);
word[63] = 0;

回答by Blue Phoenix

The following code can be used to read the input string from a user. But it's space is limited to 64.

以下代码可用于从用户读取输入字符串。但它的空间被限制为 64。

char word[64] = { '##代码##' };  //initialize all elements with '##代码##'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
    scanf_s("%c", &word[i++], 1);
}