我對 C 很陌生,對它了解不多。我想要一個解決方案,用戶可以輸入這樣的內容(在單獨的行上):
AAA
BBB
CCC
并將其存盤在這樣的變數中:
AAABBBCCC
輸入中的每一行都是一個單獨的cin. 只有一個變數可以存盤所有這些。可能嗎?
uj5u.com熱心網友回復:
您的意思是 1 個變數將存盤結果,還是在整個程式中只使用 1 個變數?如果您的意思是第一個,則考慮到您的輸入res將AAABBBCCC在運行結束時具有:
std::string tmp;
std::string res;
for (int i = 0; i < 3; i ) {
std::cin >> tmp;
res = tmp;
}
std::cout << res << std::endl;
你可以寫res = tmp,因為 std::string 多載了 operator =。
uj5u.com熱心網友回復:
如果您希望用戶以互動方式輸入字串,或者如果您想從檔案中讀取字串,那么您可以使用以下方法
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<std::string> v;
std::string s;
// Enter Ctrl-Z to terminate
while(std::cin >> s) {
v.push_back(s);
}
auto all = std::accumulate(v.begin(), v.end(), std::string(""));
std::cout << all << std::endl;
}
AAAA
DDDD
BBBB
CCCC
^Z
AAAADDDDBBBBCCCC
std::accumulate將二元謂詞作為其最后一個引數。如果您想在字串之間添加分隔符,您可以利用這一點。
// define a delimiter
std::string delim{"-"};
// lambda to concatenate string with a separator
auto addDelimiter = [=](const std::string& s1, const std::string& s2) {
std::string result{s1};
if(!s1.empty() && !s2.empty())
result = delim;
result = s2;
return result;
};
auto all2 = std::accumulate(v.begin(), v.end(), std::string(""), addDelimiter);
std::cout << all2 << std::endl;
AAAA
BBBB
CCCC
DDDD
^Z
AAAA-BBBB-CCCC-DDDD
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490488.html
