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

时间:2017-01-09 10:26:45

标签: c string

当字符串在单词之间包含空格时,在C中从键盘读取字符串的最准确方法是什么?当我为此目的使用scanf时,它没有读取带有空格的字符串。第二个选项是使用获取,但它应该是有害的(我也想知道为什么?)。另一件事是我不喜欢#39;想要使用任何文件处理概念,如fgets。

4 个答案:

答案 0 :(得分:3)

这两种方法可以读取包含不使用getsfgets的空格的字符串

  1. 您可以使用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. 如果您绝对需要scanf,则在此示例中,它会读取到行尾,除非该行的分隔符数超过指定的字符数减1。在后一种情况下,该行被截断,您将在下一个scanf调用中获得剩余的字符。

    char line[1024];
    while (scanf("%1023[^\n]\n", line) == 1) {
        // do something with line
    }
    
  3. 我还应该指出,例如,当您使用scanf从键盘读取字符串时,实际上是从具有文件指针stdin的文件中读取。所以你无法真正避免“任何文件处理概念”

答案 1 :(得分:2)

@ user3623265,

请找一个示例程序,它使用fgets从标准输入中读取字符串。

请参考一些示例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;
}

答案 2 :(得分:1)

还有第三个选项,您可以通过stdin来电阅读read()的原始数据:

#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;
}

请注意,不是每个输入都被原始复制到buf,包括尾随回报。也就是说,如果您输入Hello World,您将获得

'Hello World
'

作为输出。试试online

答案 3 :(得分:0)

如果您坚持在范围内没有FILE *,请使用getchar()。

public class DateTimeExtensions
{
    public static DateTime AddWorkHours(this DateTime dateTime, int workHours)
    {
        var workHoursPerday = 8; //Here 8 also can be configurable value if you have different working hours for different customer.
        var daysToAdd = (int) workHours/workHoursPerday; //You can have validation here to check if workHours are in exact multiplex of 8. 
        //Also you can have rounding off logic.
        dateTime.AddDays(daysToAdd);
    }
}

但一般情况下,可以接受stdout和stdin以及FILE *。您的要求有点奇怪,因为您显然不是一个高级C程序员,他不需要压制FILE *符号,我怀疑您对C IO的理解是不稳定的。

相关问题