我是一个菜鸟 C++ 学生。我在将文件读入数组结构时遇到问题。这是一项类作业,所以我不需要任何人为我编写代码,我只想知道我做错了什么。我正在阅读的文本文件格式如下:
Giant Armadillo#443#M
Hawaiian Monk Seal#711#M
Iberian Lynx#134#M
Javan Rhinoceros#134#M etc...
使用 getline()
可以正确读取带有 '#'
定界符的字符串,但不适用于 int
或 字符
。如何在检查分隔符时读取 int
或 char
?
谢谢,对不起,如果这写得不清楚,或者格式不正确。我是 SO 的新手。
#include <iostream>
#include<string>
#include <fstream>
#include <cstdlib>
using namespace std;
//Create a new structure
struct Endangered
{
string name;
int population;
char species;
};
int main () {
Endangered animals[200];
//initialize animals
for (int i=0; i<50; i++)
{
animals[i].name=" ";
animals[i].population=0;
animals[i].species=' ';
}
ifstream myFile;
myFile.open("animals.txt");
int i=0;
if (myFile.is_open())
{
while (myFile.eof())
{
//read the string until delimiter #
getline(myFile, animals[i].name, '#');
//read the int until delimiter #
getline(myFile, animals[i].population, '#');
//read the char until the delimiter
getline(myFile, animals[i].species, '/n');
i++;
}
return 0;
}
最佳答案
我确定你不能像这样从文件中读取数据:
//read the int until delimiter #
getline(myFile, animals[i].population, '#');
因为你得到了 sting 并且你想将它分配给 int 或 char 字段。
看看这个声明:
istream& getline (istream& is, string& str, char delim);
您必须将字符串作为第二个参数。您不能将 int 或 char 和 animals[i].population 传递给此函数。population 是 int 类型。
您应该首先将数据加载到某个字符串或 char* 缓冲区,然后使用正确的函数将其转换为您想要的类型。例如,寻找像 atoi 这样的函数。
总结一下。读取数据到临时缓冲区,然后转换它。
如果这对您没有帮助,我会更正代码,但您不想:)
关于c++ - 使用 getline 读取文件时遇到问题(菜鸟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15827681/