简体   繁体   English

如何用C语言读取包含空格的字符串

[英]How To Read String that contains Spaces, in C language

What is the most accurate way to read strings from the keyboard in C, when the string contains spaces in between words? 当字符串在单词之间包含空格时,从C键盘读取字符串的最准确方法是什么? When I use scanf for that purpose then it doesn't read a string with spaces.The second option is to use gets but it is supposed to be harmful(I also want to know why?).Another thing is that I don't want to use any file handling concept like fgets. 当我为此目的使用scanf时,它不会读取带空格的字符串。第二个选项是使用gets但它应该是有害的(我也想知道为什么?)。另一件事是我不知道想要使用任何文件处理概念,例如fgets。

These are 2 ways to read strings containing spaces that don't use gets or fgets 这是读取包含不使用getsfgets空格的字符串的2种方法

  1. You can use getline (POSIX 2008 may not exist in your system) that conveniently manages allocation of the buffer with adequate size to capture the whole line. 您可以使用getline (系统中可能不存在POSIX 2008)来方便地管理具有足够大小的缓冲区的分配,以捕获整个行。

     char *line = NULL; size_t bufsize = 0; size_t n_read; // number of characters read including delimiter while ((n_read = getline(&line, &bufsize, stdin)) > 1 && line != NULL) { // do something with line } 
  2. If you absolutely want scanf , in this example it reads to the end of line unless the line has more than the specified number of chars minus 1 for the delimiter. 如果您绝对需要scanf ,则在此示例中,它将读取到行尾,除非该行的分隔符数超过指定的字符数减1。 In the later case the line is truncated and you'll get the remaining chars in the next scanf invocation. 在后一种情况下,该行将被截断,您将在下一个scanf调用中获得剩余的字符。

     char line[1024]; while (scanf("%1023[^\\n]\\n", line) == 1) { // do something with line } 

I should also point out that when you read strings from the keyboard with scanf for example, you are actually reading from a file with file pointer stdin . 我还应该指出,例如,当您使用scanf从键盘读取字符串时,实际上是从文件指针stdin读取文件。 So you can't really avoid "any file handling concept" 因此,您无法避免“任何文件处理概念”

@user3623265, @ user3623265,

Please find a sample program which Uses fgets to read string from standard input. 请找到一个示例程序,该程序使用fgets从标准输入中读取字符串。

Please refer some sample C documents as to how fgets can be used to get strings from a keyboard and what is the purpose of stdin. 请参考一些示例C文档,了解如何使用fgets从键盘获取字符串以及stdin的目的是什么。

#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

i = strlen(str) - 1;
if (str[i] == '\n')
    str[i] = '\0';

printf("This is your string: %s", str);
return 0;
}

There is a third option, you can read the raw data from stdin with the read() call: 还有第三个选项,您可以通过read()调用从stdin读取原始数据:

#include <unistd.h>

int main(void) {
    char buf[1024];
    ssize_t n_bytes_read;

    n_bytes_read = read(STDIN_FILENO, buf, sizeof(buf) - 1);
    if (n_bytes_read < 0) {
        // error occured
    }
    buf[n_bytes_read] = '\0'; // terminte string

    printf("\'%s\'", buf);

    return 0;
}

Please not that every input is copied raw to buf including the trailing return. 请不要将每个输入都原始复制到buf包括尾随返回。 That is, if you enter Hello World you will get 也就是说,如果您输入Hello World您将获得

'Hello World
'

as output. 作为输出。 Try online . 在线尝试。

If you insist on not having a FILE * in scope, use getchar(). 如果您坚持在范围内没有FILE *,请使用getchar()。

  char buff[1024];
  int ch;
  int i = 0;

  while( (ch = getchar()) != '\n' )
    if(i < 1023)
      buff[i++] = ch;
  buff[i] = 0;

  /* now move string into a smaller buffer */

Generally however it's accepted that stdout and stdin and FILE * are available. 但是,通常可以接受stdout和stdin和FILE *可用。 Your requirement is a bit odd and, since you are obviously not an advanced C programmer who has an unusual need to suppress the FILE * symbol, I suspect your understanding of C IO is shaky. 您的要求有些奇怪,并且,由于您显然不是高级的C程序员,而她又非常需要抑制FILE *符号,因此我怀疑您对C IO的理解是不稳定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM