C++ 试图将文本文件读入C++;
首先,我使用的是DEVC++,这段代码的目标是能够将文本文件读入结构数组。我的文本文件是这样写的: 动物名称:动物类型:注册号:问题号 下面代码的问题是,它似乎只运行了一次while循环 我查找过类似的代码,但它用于_string()和stoi,但我不认为DEVC++运行C++11,所以我想知道是否有一种简单的方法可以修复我现有的代码,或者是否有另一种方法可以完成读取由字符串和整数组成的文本文件C++ 试图将文本文件读入C++;,c++,arrays,struct,C++,Arrays,Struct,首先,我使用的是DEVC++,这段代码的目标是能够将文本文件读入结构数组。我的文本文件是这样写的: 动物名称:动物类型:注册号:问题号 下面代码的问题是,它似乎只运行了一次while循环 我查找过类似的代码,但它用于_string()和stoi,但我不认为DEVC++运行C++11,所以我想知道是否有一种简单的方法可以修复我现有的代码,或者是否有另一种方法可以完成读取由字符串和整数组成的文本文件 #include <iostream> #include <fstream>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#define MAX 100
using namespace std;
struct Animal
{
string animalName;
string animalType;
int Registration;
int Problem;
};
int main()
{
Animal ani[MAX];
ifstream infile;
int i = 0;
infile.open("Animals.txt");
if (!infile) {
cout << "Unable to open file";
exit(1);
}
int count = 0;
while (infile.good()) {
getline(infile, ani[i].animalName, ':');
getline(infile, ani[i].animalType, ':');
infile >> ani[i].Registration, ':';
infile >> ani[i].Problem, '.';
count++;
i++;
}
infile.close();
for (int i = 0; i < count; i++) {
cout << ani[i].animalName << " ";
}
for (int i = 0; i < count; i++) {
cout << ani[i].animalType << " ";
}
for (int i = 0; i < count; i++) {
cout << ani[i].Registration << " ";
}
for (int i = 0; i < count; i++) {
cout << ani[i].Problem<< " ";
}
return 0;
}
#包括
#包括
#包括
#包括
#定义最大值100
使用名称空间std;
结构动物
{
字符串animalName;
字符串动物型;
国际注册;
智力问题;
};
int main()
{
动物ani[MAX];
河流充填;
int i=0;
infle.open(“anists.txt”);
如果(!infle){
cout>ani[i].注册':';
infle>>ani[i].问题';
计数++;
i++;
}
infle.close();
for(int i=0;i
未读取并丢弃:'
,导致血腥死亡…抱歉。在
infile >> ani[i].Problem
尝试将:'
转换为整数。这会将infle
置于失败状态
while (infile.good())
发现infle
不好,并退出循环
你将不得不按照你的计划做些事情
std::string temp;
std::getline(infile, temp, ':');
ani[i].Registration = std::stoi(temp);
要将流向上读取到,:“
分隔符,将其转换为std::string
,然后使用std::stoi
将字符串转换为整数
这是大部分的错误。但是
while (infile.good())
在读取流之前测试流是否良好。这允许流在读取时完全失败,而在使用失败的结果之前不进行任何测试
while (getline(infile, ani[i].animalName, ':') &&
getline(infile, ani[i].animalType, ':') &&
getline(infile, temp1, ':') &&
getline(infile, temp2, '.'))
{ // only goes into loop if everything was read
// may also have to eliminate a newline here
ani[i].Registration = std::stoi(temp1);
ani[i].Problem = std::stoi(temp2); //exception if bad
i++;
}
一个更好的方法是为动物
创建一个>
操作符重载,因为这样可以编写一个如下所示的主循环
while (infile>> ani[i])
{
i++;
}
这很简单,大家都很高兴。有关编写>
操作符的信息和更多的常识,请参阅。您是否尝试过调试以确定哪个状态标志是正确的?bad()
和fail())
可以帮助你解决问题。这并不完全是你问题的根源,而是一个while(infle.good())
或while(!ifile.bad())
或while(!infle.eof())
形式的循环。如果你对动物有>
的话,你可以std::vector ani(std::istream\u迭代器{},{});
阅读声明中的所有内容。
while (infile>> ani[i])
{
i++;
}