2016-04-29 89 views
1

這裏是我正在使用的示例程序。如何在C++中組合一個向量元素

while(split.good()){ 
      split >>first; 
      split >>second; 
      word=first + second; 
      //cout<< static_cast<char> (word)<<endl; 
      vec.push_back(static_cast<char> (word)); 

     } 

第一個和第二個是int值。 所以我想結合矢量的元素來製作一個完整的單詞。

感謝,

回答

0

首先改變你的循環,檢查.eof().good()是一個壞主意,見Why is iostream::eof inside a loop condition considered wrong?獲取更多信息。改爲使用:

while(split >> first && split >> second) 

檢查是否讀取了實際的值。

我誤解了這個問題,所以下面的回答並不是真正想要的,請檢查@Tas's answer

接下來我如果我理解正確,你想把整數轉換成一個字符串?這有點不清楚,但看看std::to_string()。也許你想是這樣的:

while(split >> first && split >> second) { 
    word = first + second; 
    vec.push_back(std::to_string(word)); 
} 
+0

噢,對不起的混亂,「字」是一個真正的字符值,它只是一個不好的名字我給你從添加的整數值拿到後,他們的char值被改爲char。所以當這一切結束時,我得到的是一個char元素的向量。我想知道如何將矢量的字符元素合併爲一個單詞。有點像 vec = {'h','e','l','l','o'}; 我想要一個向量vec的字符串「hello」。我希望這是有道理的,並感謝您的意見。 –

+0

@FreA猜想我誤解了你想做的事情。無論如何,@Tas的答案正是你想要做的,只是要離開這個答案,因爲它是'while'的一部分。 –

1

首先,你應該聽@Raphael Miedl's advicewhile循環。

所有的元素結合在vector成一個字,你可以使用following std::string constructor that takes two iterators

模板<類InputIt> 的basic_string(InputIt第一,InputIt最後, 常量分配器& ALLOC =分配器());

通在開始和結束vectoriterator

const std::string s{std::begin(vec), std::end(vec)}; 

這會的vec每個元素添加到std::string。另外,您也可以使用for循環:

std::string s; 
for (auto c : vec) 
{ 
    // Add each character to the string 
    s += c; 
} 
相關問題