2013-04-11 10 views
0

我是C++的新手,从文本文件读取数据行时遇到了一些麻烦。假设我在文本文件中有未知数的行,每行的格式都是相同的:int string double。唯一可以确定的是空间将分隔给定行上的每一条数据。我正在使用结构数组来存储数据。下面的代码很好,除了在每个循环之后跳过一行输入。我试过插入各种ignore()语句,但仍然无法读取每行,只读其他行。如果我在最后重写了一些getline语句,那么在第一次循环之后,将开始为变量存储错误的数据。当读取和存储文件中的数据时,其他每行数据都会被跳过

文本文件可能是这样的:

18 JIMMY 71.5 
32 TOM 68.25 
27 SARAH 61.4 


//code 
struct PersonInfo 
{ 
    int age; 
    string name; 
    double height; 
}; 
//..... fstream inputFile; string input; 

PersonInfo *people; 
people = new PersonInfo[50]; 

int ix = 0; 
getline(inputFile, input, ' '); 
while(inputFile) 
{ 
    people[ix].age = atoi(input.c_str()); 
    getline(inputFile, input, ' '); 
    people[ix].name = input;  
    getline(inputFile, input, ' '); 
    people[ix].height = atof(input.c_str()); 

    ix++; 

    getline(inputFile, input, '\n'); 
    getline(inputFile, input, ' '); 
} 

我敢肯定有更先进的方法可以做到这一点,但就像我说的,我很新的C++所以如果有只是稍作修改到上面的代码,那会很棒。谢谢!

+0

我读到了全线然后解析行成翘楚领域。 – John3136 2013-04-11 02:12:56

回答

1

您可以执行文件读取,如下所示:

int ix = 0; 
int age = 0; 
string name =""; 
double height = 0.0; 
ifstream inputFile.open(input.c_str()); //input is input file name 

while (inputFile>> age >> name >> height) 
{ 
    PersonInfo p ={age, name, height}; 
    people[ix++] = p; 
} 
+0

这个设置实际上工作。谢谢! – 2013-04-11 02:38:01

+0

@DawgPwnd欢迎您。 – taocp 2013-04-11 02:52:18

1

你所做的这整个代码可笑的复杂。

struct PersonInfo 
{ 
    int age; 
    string name; 
    double height; 
}; 

std::vector<PersonInfo> people; 
PersonInfo newPerson; 
while(inputFile >> newPerson.age >> newPerson.name >> newPerson.height) 
    people.push_back(std::move(newPerson)); 

你的问题是,因为首先你在同一时间从文件中再次读取数据的一个的每一位,从格兰文件,然后一整行,然后每一个数据位从文件的时间。也许你的意图更像这样?

std::string fullline; 
while(std::getline(inputFile, fullline)) { 
    std::stringstream linestream(fullline); 
    std::getline(linestream, datawhatever); 
    .... 
} 

顺便说一句,更地道的代码可能看起来更像是这样的:

std::istream& operator>>(std::istream& inputFile, PersonInfo& newPerson) 
{return inputFile >> newPerson.age >> newPerson.name >> newPerson.height;} 

{ //inside a function 
    std::ifstream inputFile("filename.txt"); 

    typedef std::istream_iterator<PersonInfo> iit; 
    std::vector<PersonInfo> people{iit(inputFile), iit()}; //read in 
} 

Proof it works here

+0

不幸的是,我还没有学习关于stringstream的知识,这个问题在没有它的情况下是可以解决的。我相信我会学到很多能够简化我的代码的东西,但现在我几乎坚持已经列出的内容。载体解决方案看起来很有趣,所以我打算给这个镜头。 – 2013-04-11 02:24:47

+0

@DawgPwnd:如果你对stringstream不熟悉,那么第一部分代码就是你要找的东西。 – 2013-04-11 03:55:44

相关问题