【问题标题】:I want to read a file from stdin and read each line into a string and only use getchar我想从标准输入读取一个文件并将每一行读入一个字符串并且只使用 getchar
【发布时间】:2017-09-13 03:09:32
【问题描述】:
#include <stdio.h>
#include <string.h>

int mygetchar();

int main(){
    mygetchar();
}

int mygetchar(){
    int c, i = 0;
    char line[1000];
    while ((c = getchar()) != EOF && c != '\n'){
        line[i] = c;
        i++;
    }
    line[i] = '\0';
    printf("%s\n", line);
    printf("%lu\n", strlen(line));
    return 0;
}

请看我的代码图片,我的代码只能输出一个字符串和一个文件的一行,但我想将文件的每一行存储为一个字符串并计算它们的长度,我不能使用 fgets ,我只能使用getchar函数,请大家帮忙,非常感谢。

【问题讨论】:

  • 首先你需要创建一个文件指针,然后使用 fopen()
  • 发布代码而不是链接图像
  • @Mitchel0022:如果 OP 只想从 stdin 读取数据,那为什么还要这样做?

标签: c


【解决方案1】:

由于您的代码基本上处理字符直到它到达行尾或文件结尾,您可以简单地在它周围放置 另一个 循环来执行每一行。

会是这样的:

int c = '\n'; // force entry into loop
while (c != EOF) {
    int i = 0;
    char line[1000];
    while ((c = getchar()) != EOF && c != '\n') {
        line[i] = c; // should really check for buffer overflow here.
        i++;
    }
    line[i] = '\0'; // and here.
    printf ("%s\n", line);
    printf ("%lu\n", strlen (line));
}

或者,您可以一个一个地处理所有字符,对行尾进行特殊处理(再次,您应该避免缓冲区溢出,并且您应该将公共代码移动到一个函数中):

int c, i = 0;
char line[1000];
while ((c = getchar()) != EOF) {
    // Newline is special, print and reset.

    if (c == '\n') {
        line[i] = '\0';
        printf ("%s\n", line);
        printf ("%lu\n", strlen (line));
        i = 0;
    } else {
        line[i] = c;
        i++;
    }
}
// If data at end without newline.

if (i != 0) {
    line[i] = '\0';
    printf ("%s\n", line);
    printf ("%lu\n", strlen (line));
}

【讨论】:

  • 我可能会认为do {} while() 循环会更好,而不是int c = '\n'; // force entry into loop
  • @胡云飞:如果你觉得这个答案有帮助,你可能不仅要接受它,还要点赞它。这是常见的礼仪,除非你有理由不这样做。
  • 一定要这样做
猜你喜欢
  • 1970-01-01
  • 2019-11-11
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多