【发布时间】:2020-11-02 11:53:21
【问题描述】:
美好的一天,我正在努力从 .txt 文档中读取文件,我们将不胜感激。
代码差不多完成了,它运行没有错误,但它不会读取存储数据的文件。
数据存放在文档下:idnumbers.txt
代码:
using namespace std;
int year;
int read(char*);
void display(char*, int);
void display_birthday(char*, int);
int main()
{
char ids[MAX_CHAR];
int count=read(ids);
display(ids, count);
return 0;
}
int read(char*array){
FILE*file=fopen("idnumbers.txt","r");
printf("\nPrinting from file...\n");
char c;
int count=0;
for(int i=0;i<MAX_CHAR;i++){
if(fscanf(file,"%c",&c)==EOF){
break;
}
else {
*(array+i)=c;
count++;
}
}
return count;
}
void display(char*array, int count){
for(int i=0;i<count;i++){
printf("%c",*(array+i));
}
}
void display_birthday(char*array, int count){
for(int i=0;i<count;i++){
if(*(array+i)=='_'){
char word[3]={*(array+i+1),*(array+i+2)};
int year= atoi(word);
if (year<=20){
year+=2000;
}
else{
year+=1900;
}
printf("\nYear: %d/%c%c/%c%c",year,*(array+i+3),*(array+i+4),*(array+i+5),*(array+i+6));
}
}
}
代码获取名为:idnumbers.txt 的文档并读取内容。然后它应该打印每一行的出生日期。
示例输出:
Date born: 1978/03/04
Date born: 1989/04/05
Date born: 1990/02/01
Date born: 1994/08/07
Date born: 1987/03/08
Date born: 1978/12/12
Date born: 2001/08/06
Date born: 2010/12/23
Date born: 2008/01/09
Date born: 1999/11/22
我不确定如何将 .txt 文件插入到 stackoverflow 中,所以我只是复制了内容。
_7803045678087
_8904050876092
_9002017896054
_9408072345087
_8703083456098
_7812120867087
_0108068675087
_1012239687087
_0801090675086
_9911220768082
【问题讨论】:
-
在 C++ 文件中通常由
std::ifstream读取,使用FILE*更多的是C 方式。使用它,你的情况就差不多完成了(提示:operator>>)。 -
还应检查文件是否已成功打开。
-
您使用的是哪本 C++ 教科书,它给出了从文件读取的示例?无论是哪一本教科书,您都应该认真考虑扔掉它,并获得一本更好的教科书,该教科书正确解释了如何在现代 C++ 中读写文件。
标签: c++ pointers file-handling