0

我使用代码块编写了一个 C++ 程序,在最后一刻我决定使用 empress,这是我们用来做实验室的学校服务器,结果发现它不起作用!这意味着什么?我的程序不对吗?还是可能是编译器问题?我通常使用 linux ubuntu 使用代码块来进行编程。我使用 Windows 测试了该程序,它也可以工作。为什么它不在服务器上运行?

这是我认为导致问题的代码:

bool dictionary::insertWordsIntoDict(string fileName)
{

   ifstream inp;
   string word;
   vector<string> vec;
   inp.open(fileName.data());

   if(inp.good())
   {

     while(!inp.eof())
     {
      inp>>word;
      vec.push_back(word);

     }
    string temp;
    string temp2= "#.txt";

     for(int i=0 ; i<vec.size() ; i++)
     {
          temp = vec[i];
          temp2[0] = tolower(temp[0]);
          cout<<temp<<endl;
          AddWord(temp.data(), temp2);
     }

   }//end of if statement

  else
  {
     cout<<":(  File does not exist! "<<endl;
     return failure;
  }

}// end of function insert words
4

2 回答 2

2

while(!inp.eof())不是从文件中读取的好方法。特别是,如果它由于 EOF 以外的其他原因无法读取,则条件永远不会为假,并且您的循环将永远运行。

编写这种循环的正确方法是:

while(inp >> word)
 {
  vec.push_back(word);
 }

在这里,如果由于任何原因无法从输入流中读取,inp >> word将评估为 false 。word

如果没有更多细节,我不能确定这是你的问题,但它不会受到伤害。

于 2013-03-15T01:17:44.890 回答
1

好吧,至少有一个问题,您eof在循环条件中使用,您应该像这样修改:

while( inp >> word)
 {
  vec.push_back(word);

 }

这个先前的线程涵盖了为什么循环条件内的 iostream::eof 被认为是错误的?.

于 2013-03-15T01:17:56.800 回答