This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(4个答案)
7年前关闭。
我正在尝试打开一个整数文件,该文件将传递到保存数组的结构中,但是当我尝试这样做时,我在输出中得到一个添加的零,而当我向程序中添加更多时,该内核就被转储了。 ,所以我不确定自己在做什么错以及如何解决。
该文件是123456,但随后我得到1234560>作为输出,当我添加其余代码时,将出现核心转储。我不确定传递问题还是我的变量不正确,但是如果有人可以帮助我,那将意味着很多。
当然,通常也应该使用
(4个答案)
7年前关闭。
我正在尝试打开一个整数文件,该文件将传递到保存数组的结构中,但是当我尝试这样做时,我在输出中得到一个添加的零,而当我向程序中添加更多时,该内核就被转储了。 ,所以我不确定自己在做什么错以及如何解决。
#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++;
}
}
该文件是123456,但随后我得到1234560>作为输出,当我添加其余代码时,将出现核心转储。我不确定传递问题还是我的变量不正确,但是如果有人可以帮助我,那将意味着很多。
最佳答案
通常,您要检查阅读尝试是否成功:
while(inf>>theHand.handCards[i])
{
theHand.totalCards++;
cout<<theHand.handCards[i];
i++;
}
当然,通常也应该使用
std::vector
而不是数组,但是我想我们可以将其留给另一个问题。