2013-02-27 62 views
0

我对C++比较陌生,并且从文本文件中获取输入时遇到了困难。从文本文件中获取信息的问题C++

相关代码:

vector<string> nutrientName; 
vector<float> nutrientAmount; 
vector<string> nutrientUnits; 
vector<float> nutrientCalories; 

ifstream nutrientFile; 
nutrientFile.open(nutrientFileName); 
float newAmount = 0; 
string newUnit; 
float newCalories = 0; 

while (!nutrientFile.eof()) 
{ 
    int place = 0; 
    char nameArray [50]; 


    while(c != ';') 
    { 
     if (c != '\n') 
      nameArray[place] = c; 

     c = nutrientFile.get(); 
     place++; 
    } 

    string newName(nameArray, place); 
    nutrientName.push_back(newName); 

    nutrientFile >> newAmount; 
    nutrientAmount.push_back(newAmount); 

    nutrientFile >> newUnit; 
    nutrientUnits.push_back(newUnit); 

    nutrientFile >> newCalories; 
    nutrientCalories.push_back(newCalories); 

} 

nutrientFile.close(); 

输入是关于他们的成分和一些营养的事实成立这样的列表:

Ingredient1(1+字); amountOfUnitsInServingSize(float)unitType(1个字)caloriesPerServing(float) Ingredient2(1+ words); amountOfUnitsInServingSize(float)unitType(1个字)caloriesPerServing(float)

我的问题是,当我试图从文件中带入东西时,它会卡在任何一个while循环中(如果内部的一个被注释掉)。当我抛出调试代码时,它表明它实际上没有从文件获取任何输入。

预先感谢您!

+0

要简单地定义nameArray为字符串,并使用<<操作符来提取nameArray。之后,你可以在令牌中分隔这个字符串。 – user1929959 2013-02-27 23:47:26

回答

0

有2或3个问题。

看评论:

while (nutrientFile.good() == true) // use good() its more safe with your implementation 
{ 
     int place = 0; 
     char nameArray [50]; 
     char c;       // not defined  

     c = nutrientFile.get();   // was not init 
     while (c != ';') 
     { 
      if (c != '\n') 
        nameArray[place] = c; 
      c = nutrientFile.get(); 
      place++; 
     } 
     string newName(nameArray, place); 
     nutrientName.push_back(newName); 
     nutrientFile >> newAmount; 
     nutrientAmount.push_back(newAmount); 
     nutrientFile >> newUnit; 
     nutrientUnits.push_back(newUnit); 
     nutrientFile >> newCalories; 
     nutrientCalories.push_back(newCalories); 
} 

好运;)

+0

谢谢!这解决了这个问题(好吧,这个)。其他几个人突然出现,但我设法解决了这些问题。这一个只是不会为我自己修复。 – 2013-02-28 06:14:05

0

检查inner while循环中的eof。