2015-11-14 153 views
-1

有沒有辦法使用std :: cin來追加到字符串,而不是替換裏面的內容?使用cin追加到字符串C++

或者還有更好的選擇嗎?

+0

爲什麼你不能只是'cin'到一個不同的字符串,然後使用'std :: string :: operator +'將這些字符串追加到一起呢? –

回答

0

你可以嘗試這樣的事情:

#include <iostream> 
#include <iterator> 
#include <string> 

int main() 
{ 
    std::istream_iterator<std::string> it(std::cin); 
    std::istream_iterator<std::string> end_it; 
    std::string str; 
    for (int i = 0; i < 3; ++i) 
     if (it != end_it) { 
      str += *it; 
      if (i != 2) 
       ++it; 
     } else { 
      break; 
     } 
    std::cout << "Res: " << str << "\n"; 
} 

而且更易於使用只有兩個std::string變量, 一個用於電流輸入,另一個用於積累。