2012-01-17 75 views
-2

我有一個C/C++的問題。 下面是我的代碼。 一旦菜單被選項1擊中,它將按照正常運行並顯示結果,並重新顯示菜單。 但是之後我將無法輸入任何內容。 這是爲什麼呢? 在此先感謝那些幫助,歡呼!C++ C循環問題

EDITTED,這是我的整個主

int main() 
{ 
int Option; 
Menu m; 
do 
{ 
    m.showMenu(); 
    cout<<"Please enter your choice:"; 
    cin>>Option; 



    if (Option == 1) 
    { 

     int scenario = 0; 
     string Lines; 
     Mobile mobileObj; 

     freopen("file.txt","r",stdin); 


     while(true) 
     { 
      getline(cin,Lines); 
      while(Lines.length() > 1 && Lines[0] == ' ') Lines = Lines.substr(1); 
      if(Lines.length() == 1 && Lines[0] == ' ') continue; 

      if(scenario == 0) 
      { 
       if(Lines == "Mobile Phones & Accessories Classifieds") 
       { 
        scenario = 1; 
        getline(cin,Lines); 
        continue; 
       } 
      } 

      else if(scenario == 1) 
      { 
       if(Lines[0] == '*') continue; 
       else scenario = 2; 
      } 

      else if(scenario == 2) 
      { 
       if(Lines[0] == '[') 
       { 
        for(unsigned int i=0;i<Lines.length();++i) 
        { 
         if(Lines[i] == ']') 
         { 
          mobileObj.mobDevName = Lines.substr(i+1); 
          break; 
         } 
        } 
       } 

       else if(Lines.length() > 11 && is_number(Lines[0]) && is_number(Lines[1]) && is_number(Lines[10])) 
       { 
        mobileObj.dateOfPub = Lines.substr(0,11); 
       } 

       else if(Lines.length() >= 5 && Lines[0] == 'S' && Lines[1] == '$') 
       { 
        mobileObj.price = Lines; 
        v_Mob.push_back(mobileObj); 
       } 

       else if(Lines == "Browse Marketplace Listings") break; 
      } 

     } 


    cout<<("[Mobile device Name] â€「 [Date of publish] â€「 [Mobile phones’ pricings]\n"); 

    for(unsigned int i=0;i<v_Mob.size();++i) 
    { 
     cout << i+1 << ") "; 
     v_Mob[i].print(); 
    } 

    cout<<"\n"; 
    cout<<"Going back to main menu ...\n"; 
    cout<<"\n"; 
} 

else if (Option == 2) 
    { 
     cout<<"hi\n"; 
    } 

}while(Option != 0); 

return 0; 
} 
+0

哪裏是代碼的其餘部分?例如,我們想知道結束'do'循環的條件是什麼。 – 2012-01-17 20:51:10

回答

1

後第一循環stdin現在的文件 「file.txt」,但由於:

freopen("file.txt","r",stdin); 

所以你不能從輸入任何內容命令提示符。

如果需要從「file.txt的」閱讀使用ifstream

std::ifstream in("file.txt"); 
if (in.is_open()) 
{ 
    while (std::getline(in, Lines)) 
    { 
     // ... 
    } 
    in.close(); 
} 
+0

使用'fopen()'並得到一個新的'FILE *' – 2012-01-17 20:56:34

+0

嗨hmjd,我試過改用ifstream,它掛在我身上。我不確定爲什麼會這樣。 – Andres 2012-01-17 21:23:35

+0

@Andres,用'while'循環的終止條件更新答案。 – hmjd 2012-01-17 21:30:38