2013-08-19 49 views
1

我正在進行一項練習,將字詞存儲在<vector>string s中,然後將所有字母轉換爲大寫,並且每行打印出8個字。除了toupper()我的代碼的一部分,一切正常。這一切是:不能讓toupper與矢量一起工作

vector<string> words; 
string theWords; 
string word; 

while(cin >> word) 
    words.push_back(word); 

for(auto &i : words) { 
    word = i; 
    for(auto &j: word) 
     j = toupper(j); 
} 

int k = 0; 
for(auto i : words) { 
    cout << i << " "; 
    ++k; 
    if(k % 8 == 0) 
     cout << endl; 
} 
+0

歡迎來到Stack Overflow。爲了最好地回答問題,你應該總是嘗試發佈一個[sscce](http://sscce.org/),你期望輸出/行爲是什麼以及你看到的輸出/行爲。如果您有編譯錯誤,請發佈編譯器錯誤。 http://stackoverflow.com/questions/how-to-ask – kfsone

+0

我以前沒有遇到過。我將來會這樣做,謝謝。 – spartanhooah

回答

2

你存儲在word新更新的字符串,但您應該更新i

更改此

for(auto &i : words) { 
    word = i; 
    for(auto &j: word) // word is updated, but your vector is not 
     j = toupper(j); 
} 

...這樣的:

for (auto &i : words)  // for every string i in words vector 
    for (auto &j : i)  // update your i, not word 
     j = toupper(j); 
2

您正在將臨時字符串「word」轉換爲大寫,然後將disca編輯它。

string word; 

for(auto &i : words) { 
    word = i; <<-- here 
    for(auto &j: word) 
     j = toupper(j); 
} 

你需要做的是

for(auto &i : words) { 
    for(auto &j: i) 
     j = toupper(j); 
} 

現場演示這裏:http://ideone.com/pwQBQr#

0

word = i使用的字符串拷貝構造函數的表達式。 word不是向量中的那個。

0

晚會有點晚,但這裏是沒有額外循環的版本。

for(auto &i : words) 
    std::transform(i.begin(), i.end(), i.begin(), ::toupper);