所以這是一段時間,因爲我在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塊(除了最後一個),然後繞回身邊,並執行相應的方法。這一切都有效,所以這只是一個小小的煩惱,但我想了解這種行爲。
這些數字是找到的字符串索引的調試輸出,不存在於非測試執行中。
是'run converter'的輸入嗎?你是否希望通過一次調用'cin >> run'來獲得整個字符串「運行轉換器」?流提取操作符('<<')停止在空白處。如果你需要整個字符串,可以使用'std :: getline(cin,run);' – Chad