您的問題是有關您的輸入定義:
- 你有3個串讀
- 你有5個字由searated空格
- 有6種方法可以將字組合成字符串
因此,如何將你的PROGRAMM猜測這是之間的權利conbination:
BNA, Boston, Red Stokings NA
BNA, Boston Red, Stockings NA
BNA, Boston Red Stockings, NA
BNA Boston, Red, Stockings NA
BNA Boston, Red Stockings, NA
BNA Boston Red, Stockings, NA
基本上有兩種可能性繼續。
備選方案1:引入分隔符(例如上面的逗號)。
然後,您可以procedd如下:
string team1, team2, team3;
getline (cin /*or another sream*/, team1, ','); // use a delimiter
getline (cin, team2, ','); // again stop reading at the delimiter
getline (cin, team3); // here a delimiter is not expected, so read until NL.
備選方案2:使用允許值
如果預期輸入,帶或不帶空格的列表是已知的,你可以的固定名單讀取字符串,並讓程序進行嘗試並驗證它的猜測是否僅與允許的值相對應。
這裏一個小例子:
set<string> teams { "BNA", "BOSTON RED STOCKINGS", "CHICAGO WHALES", "NA" }; // set of valid input strings
string input;
getline(cin, input); // get input line
transform(input.begin(), input.end(), input.begin(), ::toupper); // convert to uppercase (case sensitive might be to error prone)
vector<string> parts { istream_iterator<string>{stringstream(input)}, istream_iterator<string>{} }; // tokenize in words
// test potential combination of words
for (int i = 1; i < parts.size() - 1; i++) { // length in words of the first sub string
for (int j = 1; j < parts.size() - i; j++) { // length in words of the second sub string
string s1,s2,s3;
for (int k = 0; k < parts.size(); k++) { // construct substring;
if (k < i) s1 += (k == 0 ? "" : " ") + parts[k];
else if (k < i + j) s2 += (k == i ? "" : " ") + parts[k];
else s3 += (k == i + j ? "" : " ") + parts[k];
}
cout << "Possible entry: " << s1 << " // " << s2 << " // " << s3<<endl;
if (teams.find(s1) != teams.end() && teams.find(s2) != teams.end() && teams.find(s3) != teams.end())
cout << "Valid entry found =======>" << s1 << " // " << s2 << " // " << s3 << endl; // FOUND => DO SOMETING
}
}
// IF END OF LOOP BUT NO VALID VALUE COMBINATION FOUND, there is an error in the input
第一個和第三個字符串是否有空格? – polarysekt 2014-09-13 00:22:59
請添加您的代碼,以便更容易地檢測問題或幫助您。 – VicM 2014-09-13 00:24:42
更明確的是向我們展示代碼。 – 0x499602D2 2014-09-13 00:31:27