【发布时间】:2014-03-10 14:28:44
【问题描述】:
我在读取数据时遇到问题,过去一个小时我一直在研究它,但没有更好的结论。下面粘贴的是我的代码的 sn-ps 和我正在阅读的文件表格。该文件已正确打开,结构声明也如下所示。我相信解决方案很简单,而且由于在这个项目上工作时间过长,我想太多了,但这是我的解释。
数据文件被正确打开,所有数据都被读入适当的位置,直到 while(infile>>temp.startDistance.....) 部分。在这一点上,我的目标是在读取随机僵尸的数量后,在每一轮中明确地读取僵尸(请参阅数据文件的格式)。在之前读取数据的情况下,我使用 getline,而不是 sscanf 对从 getline 接收到的字符串的 c 字符串版本进行提取,以提取适当的数据。由于显式僵尸只是用空格分隔数据进行格式化,因此我想使用 >> 操作符来提取数据。我已经读过混合 getline 和 this 是不好的做法,但我相信在这种情况下它是有意义的。当一个 0(n) 函数 (>>) 就足够时,运行 getline()、strcpy() 和 sscanf() 将毫无意义(这将测试速度)。
我的问题是它在第 1 轮中正确读取了显式僵尸。但是,当它到达“---”表示新一轮时,因此从 while 循环的开头开始,它完全退出两个循环。我研究了标志,并认为会发生故障位,程序计数器将返回到初始 while 循环以在新一轮中读取。我尝试过使用 peek() 没有成功,而一个捷径肯定会让我在某些测试用例中失败。
我只是专注于修复最后的 while 循环,而不是重做下面列出的整个代码。如果需要更多信息,我很乐意添加更多信息。谢谢!
struct zombiesPerRound{
unsigned int round;
unsigned int numZombies;
};
struct zombie{
unsigned int startDistance;
unsigned int speed;
unsigned int health;
string name;
};
string line;
vector <zombiesPerRound> randomZombies;
list <zombie> masterList;
ifstream infile(inputFile);
if(infile.is_open()){
//Read in the Player Information
getline(infile,line);
char *read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Quiver_Capacity: %u",&settings.numArrows);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Random_Seed: %u",&settings.randomSeed);
srand(settings.randomSeed);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Max_Rand_Distance: %u",&settings.maxDistance);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Max_Rand_Speed: %u",&settings.maxSpeed);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Max_Rand_Health: %u",&settings.zombieHealth);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Player_Health: %u",&settings.playerHealth);
delete read;
while(!infile.fail()){
getline(infile,line);
if(!line.substr(0,1).compare("-"))
continue;
zombiesPerRound randZombie;
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Round: %u",&randZombie.round);
delete read;
getline(infile,line);
read=new char[line.length()+1];
strcpy(read,line.c_str());
sscanf(read,"Num_Zombies: %u",&randZombie.numZombies);
delete read;
randomZombies.push_back(randZombie);
zombie temp;
//Read in the explicit zombies
while(infile >> temp.startDistance >> temp.speed >> temp.health >> temp.name){
masterList.push_back(temp);
}
}
}
infile.close();
//test1.txt
Quiver_Capacity: 10
Random_Seed: 2049231
Max_Rand_Distance: 50
Max_Rand_Speed: 60
Max_Rand_Health: 1
Player_Health: 10
---
Round: 1
Num_Zombies: 25
150 300 15 FoxMcCloud
2 3 6 FalcoLombardi
100 1 100 SlippyToad
---
Round: 3
Num_Zombies: 50
20 10 20 DarkLink
【问题讨论】: