从文本文件c++; 我对C++很陌生,从文本文件中输入的问题一直很难。

从文本文件c++; 我对C++很陌生,从文本文件中输入的问题一直很难。,c++,C++,相关代码: vector<string> nutrientName; vector<float> nutrientAmount; vector<string> nutrientUnits; vector<float> nutrientCalories; ifstream nutrientFile; nutrientFile.open(nutrientFileName); float newAmount = 0; string newUnit; f

相关代码:

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();
vector nutrientName;
载体营养量;
载体营养单位;
载体营养素;
ifstream文件;
打开(nutrientFileName);
浮动新金额=0;
字符串新单位;
浮点数=0;
而(!nutrientFile.eof())
{
int place=0;
字符名称数组[50];
而(c!=“;”)
{
如果(c!='\n')
nameArray[place]=c;
c=nutrientFile.get();
place++;
}
字符串newName(nameArray,place);
nutrientName。推回(newName);
nutrientFile>>新金额;
nutrientAmount.向后推(新数量);
nutrientFile>>新单元;
nutrientUnits.向后推(新单元);
nutrientFile>>新卡路里;
NutrientCarries.向后推(新卡路里);
}
nutrientFile.close();
输入的是成分列表和一些营养事实,如下所示:

Ingredient1(1+字);AmountFunitsInservingSize(float)unitType(1个字)caloriesPerServing(float) Ingredit2(1+字);AmountFunitsInservingSize(float)unitType(1个字)caloriesPerServing(float)

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


提前谢谢你

同时检查内部while循环上的eof。

有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);
}

祝你好运;)

只需将nameArray定义为字符串并使用,谢谢!这解决了这个问题(好吧,这一个)。其他一些出现了,但我设法解决了这些问题。对我来说,这件事不容易解决。