繁体   English   中英

尝试获取每一行,但仅返回循环中的第一个字符

[英]Trying to get each line, but only returns first character in the loop

所以我有一个while循环来读取文本文件的注释,如下所示。 评论后可能会有一些事情,所以不应该排除。 这是我的代码,如下所示:

int i = 0;
while(!feof(fd) || i < 100) {
    fscanf(fd, "#%s\n", myFile->comments[i]);
    printf("#%s\n", myFile->comments[i]);
    getch();
    i++;
}

评论格式:

# This is a comment
# This is another comment

知道为什么它只返回第一个字符吗?

编辑:

这是我的评论数组:

char comments [256][100];

comment数组允许256个字符串,每个字符串最多100个字符。
扫描集" %99[^\\n]"将跳过前导空格,最多扫描99个字符(以允许终止'\\ 0')或换行符,以先到者为准。
if条件将打印该行,并在带注释的行上增加i

int i = 0;
char comments[256][100];
while( i < 256 && ( fscanf(fd, " %99[^\n]", comments[i]) == 1)) {
    if ( comments[i][0] == '#') {
        printf("%s\n", comments[i]);
        i++;
    }
}

因为带有%s scanf读到' ''\\n'EOF 使用类似fgets东西。

"%s"不节省空间。

它读取并丢弃前导空格,然后将非空格保存到myFile->comments[i]

// reads "# This ", saving "This" into myFile->comments[i]
fscanf(fd, "#%s\n", myFile->comments[i]);
// Prints "This"
printf("#%s\n", myFile->comments[i]);
// reads and tosses "i"
getch();

// next fails to read "s a comment" as it does not begin with `#`
// nothing saved in myFile->comments[i]
fscanf(fd, "#%s\n", myFile->comments[i]);
// output undefined.
printf("#%s\n", myFile->comments[i]);

相反,请避免使用scanf() 要读取一行输入,请使用fgets()

char buf[100];
while (fgets(buf, sizeof buf, stdin)) {
  if (buf[0] == '#') printf("Comment %s", &buf[1]);
  else printf("Not comment %s", buf);
}

暂无
暂无

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

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