问题描述
早上好,我正在努力从.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代码,用“ c”标记您的问题更合适。您的代码看起来还不错,只是您没有激活功能display_birthday
。我用C语言测试了您的代码,必须更改一些头文件,激活生日打印,删除使用的命名空间,然后将代码另存为.c
文件。
#include <stdio.h>
#define MAX_CHAR 65500
#include <stdlib.h>
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);
display_birthday(ids,count);
return 0;
}
您的工作量过大。由于输入文件是txt文件。您可以将每行输入一个字符串,然后逐行输入。将整个文本文件检索到单个数组中是一个很奇怪的想法。
,由于您需要c ++,因此我提供以下典型的c ++代码供您参考。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string str;
int year;
char schar str2[3]={},month[3]={},day[3]={};
std::ifstream file("idnumbers.txt");
while ( std::getline(file,str) )
{
if (str[0] == '_')
{
str.copy(str2,2,1); // copy year into str2
year = std::stoi(str2); // convert to integer
if (year > 20) year += 1900;
else year += 2000;
str.copy(month,3); // copy two month bytes
str.copy(day,5); // copy two day bytes
std::cout << "Date born: " << year << "/" << month <<"/" << day << std::endl;
}
}
file.close();
return 0;
}