C++ 使用while(inf.good)读取整数文件
我试图打开一个整数文件,该文件将被传递到一个包含数组的结构中,但当我尝试打开时,输出中会增加一个零,当我向程序中添加更多时,核心会被转储,因此我不确定我做错了什么以及如何修复它C++ 使用while(inf.good)读取整数文件,c++,io,C++,Io,我试图打开一个整数文件,该文件将被传递到一个包含数组的结构中,但当我尝试打开时,输出中会增加一个零,当我向程序中添加更多时,核心会被转储,因此我不确定我做错了什么以及如何修复它 #include <iostream> #include <string> #include <iomanip> #include <fstream> #include <cmath> #include <cstdlib> using namespa
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
struct Hand
{
int handCards[52];
int totalCards;
};
struct Card
{
char rank;
char suit;
};
void OpenFile (ifstream&, string&);
void ReadFile (ifstream&, Hand&);
void ProcessRank (Hand&, int CardRank[]);
void ProcessSuit (Hand&, int CardSuit[]);
char GetRank (int);
char GetSuit (int);
void PrintCard (Card);
Card ConvertRaw (Hand);
void PrintHand (Card, Hand);
int main()
{
ifstream inf;
string filename;
Hand theHand;
Card aCard;
int CardRank[13];
int CardSuit[4];
OpenFile(inf, filename);
ReadFile(inf, theHand);
}
void OpenFile (ifstream &inf, string &filename)
{
cout<<"What is the name of the file?" <<endl;
cin>>filename;
inf.open(filename.c_str());
if (inf.fail())
{
cout<<"Sorry, that file doesn't exist" <<endl;
exit(1);
}
else
cout<<"Success!" <<endl <<endl;
}
void ReadFile (ifstream &inf, Hand &theHand)
{
theHand.totalCards=0;
int i=0;
while(inf.good())
{
inf>>theHand.handCards[i];
theHand.totalCards++;
cout<<theHand.handCards[i];
i++;
}
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
结构手
{
国际名片[52];
积分卡;
};
结构卡
{
字符秩;
炭服;
};
void OpenFile(ifstream&,string&);
无效读取文件(ifstream&,Hand&);
void ProcessRank(Hand和int CardRank[]);
无效工艺套装(手工和内部卡式套装[]);
字符GetRank(int);
chargetsuit(int);
作废打印卡(卡片);
卡片(手);
作废打印手(卡片、手);
int main()
{
ifstream-inf;
字符串文件名;
手拉手;
卡学院;
int CardRank[13];
int CardSuit[4];
OpenFile(inf,文件名);
读取文件(inf,theHand);
}
void OpenFile(ifstream和inf、字符串和文件名)
{
cout通常,您需要检查您的读取尝试是否成功:
while(inf>>theHand.handCards[i])
{
theHand.totalCards++;
cout<<theHand.handCards[i];
i++;
}
while(inf>>手牌[i])
{
totalCards++;
coutThis解决了在一个额外的0中读取文件的问题,谢谢。但是核心被转储到完整程序中的问题仍然存在,如果可以的话,我可以添加其余的代码help@RayRomank:您需要确定核心转储发生的位置-哪个函数的哪一行。这是调试器擅长的,qui通常,当调试器向您指出原因时,原因是显而易见的。有时,原因并非如此;然后,您通常会在其他地方遇到问题,您的写入超出了分配的内存的范围,而崩溃站点正是在尝试分配内存时触发转储的代码。