我是noob C++的學生。我無法將文件讀取到數組結構中。這是一個班級任務,所以我不需要任何人爲我做代碼,我只是想知道我做錯了什麼。我讀的文本文件的格式爲這樣:使用getline讀取文件時遇到問題(noob)
Giant Armadillo#443#M
Hawaiian Monk Seal#711#M
Iberian Lynx#134#M
Javan Rhinoceros#134#M etc...
使用getline()
工作正常讀取與'#'
分隔字符串,但不與int
或char
工作。在檢查分隔符時,如何閱讀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;
}
使用'「\ n'',而不是'」/n'' – 2013-04-05 07:05:47