【问题标题】:Reading and printing characters from a user defined text file从用户定义的文本文件中读取和打印字符
【发布时间】:2013-12-02 19:53:30
【问题描述】:

我正在尝试研究如何逐字符打印用户定义的文本文件的内容。我相信我已经正确地检索了文件,但我不确定如何打印每个字符。

#include <stdio.h>
#include <ctype.h>

#define ELEMENT 300
#define LENGTH 20
void main(char str[ELEMENT][LENGTH])
{
FILE *infile;

char textfile[1000];
char read_char;
int endoff;
int poswithin = 0;
int wordnum= 0;

printf("What is the name of your text file?: ");
scanf("%s", &textfile);
infile=fopen(textfile,"r");    

if (infile == NULL) {
 printf("Unable to open the file."); 
}
else
{
endoff=fscanf(infile,"%c",&read_char);
while(endoff!=EOF);
{

这就是我认为我陷入困境的地方。第一个字符被读入变量 read_char 但它似乎没有打印任何东西?

if(read_char>=65&&read_char<=90 || read_char<=65)
{
    str[wordnum][poswithin]=read_char;
    printf("%c", read_char);
    poswithin++;
}
else
{
 str[wordnum][poswithin]=(char)"\n";
 poswithin=0; wordnum++;
}
endoff=fscanf(infile, "%s", &read_char);
 }
}
fclose(infile);
}

【问题讨论】:

    标签: c++ file printing


    【解决方案1】:

    在第二次调用fscanf时输入格式说明符

    endoff=fscanf(infile, "%s", &read_char);
    

    应该是

    endoff=fscanf(infile, "%c", &read_char);
    

    还有,

    str[wordnum][poswithin]=(char)"\n";
    

    不应将字符串文字转换为 char 并且可能应该添加 NULL 终止符而不是换行符:

    str[wordnum][poswithin]='\0';
    

    最后,您不应该尝试将str 声明为main 的参数。

    char str[ELEMENT][LENGTH];
    int main() // or int main(int argc, char* argv[])
    

    【讨论】:

    • 感谢您的更正,但我仍然不确定如何打印我正在阅读的字符?再次感谢。
    • printf("%c", read_char); 是正确的。请注意,控制台输出可能是行缓冲的,因此在您打印换行符 \n 或使用 fflush(stdout); 显式刷新之前可能不会出现在屏幕上
    • 它仍然没有在控制台上打印任何东西,我不知道为什么。
    【解决方案2】:

    使用fscanf%c 格式说明符对于从文件中读取单个字符来说是多余的。

    尝试fgetc 读取一个字符。该函数避免了解析格式说明符字符串和可变数量的参数的开销。

    一种更有效的方法是分配一个缓冲区或数组并使用fread 从文件中读取“块”字符。然后您可以扫描缓冲区或数组。与读取单个字节的许多调用相比,这具有更少的函数调用开销。有效缓冲区大小是 512 的倍数,以符合磁盘驱动器扇区大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多