2014-02-11 33 views
0

所以這是一段時間,因爲我在C++中做了任何事情,但是我從while循環中得到了一個非常奇怪的行爲。它旨在允許用戶執行無限數量的命令,並根據字符串的內容確定執行哪些命令。雖然循環不等待方法完成

這裏有感興趣的代碼:

string run; 
    size_t found; 
    bool understood; 
    while (true) 
    { 
      run = ""; 
      found = string::npos; 
      cout << "Please enter command(s)" << endl; 
      cout << "\> "; 
      cin >> run; 
      found = run.find("convert"); 
      cout << found << endl; 
      understood = false; 
      if (found != string::npos) 
      { 
        cout << "Converting DNA" << endl; 
        understood = true; 
        convert(); 
      } 
      found = run.find("purify"); 
      if (found != string::npos) 
      { 
        cout << "Purifying DNA" << endl; 
        purify(); 
        understood = true; 
      } 
      found = run.find("build"); 
      if (found != string::npos) 
      { 
        cout << "Building overlaps" << endl; 
        buildOverlaps(); 
        understood = true; 
      } 
      found = run.find("close"); 
      if (found != string::npos) 
      { 
        cout << "Goodbye" << endl; 
        break; 
      } 
      if (understood == false) cout << "I'm sorry, I didn't understand you" << endl; 
    } 

我從原來的方法,剛剛參與,如果移動字符串==「字符串」,使多個命令可以通過在同一行執行。然而,當我運行這個新的代碼,我得到

Please enter command(s) 
> run converter 
(some long, nonzero, number) 
I'm sorry, I didn't understand you 
Please enter command(s) 
> 0 
Converting DNA 

因此,基本上,它似乎把字符串中,跳過if塊(除了最後一個),然後繞回身邊,並執行相應的方法。這一切都有效,所以這只是一個小小的煩惱,但我想了解這種行爲。

這些數字是找到的字符串索引的調試輸出,不存在於非測試執行中。

+1

是'run converter'的輸入嗎?你是否希望通過一次調用'cin >> run'來獲得整個字符串「運行轉換器」?流提取操作符('<<')停止在空白處。如果你需要整個字符串,可以使用'std :: getline(cin,run);' – Chad

回答

2

如果輸入是

> run converter 

然後你得到你的輸入

cin >> run; 

不會爲你工作(operator>>斷裂上的空白)的方式。第一次通過循環時,它會嘗試找到一個「運行」字符串,然後它會再次嘗試找到一個「轉換器」字符串。如果你想處理整條生產線,你應該這樣做:

std::getline(std::cin, run); 
+0

真棒,更改cin >>運行到getline(cin,運行),它完美的作品 – Dustin

0

您應該在每個if(found != string::npos)塊的末尾包含一個continue;

這樣,如果它執行該塊,它將跳過另一個塊,並重新啓動while循環。

+0

如果他想運行多個命令,在每個條件塊的末尾添加「continue」將不允許。 –

+1

我曾經有一個繼續,但那麼你不能運行多個命令 – Dustin