2011-03-23 163 views
3

使用以下控制檯應用程序我將每個字符串轉換爲大寫字母。但是輸出中的字符串值保持不變。我在這裏做錯了什麼。任何有關這樣做的幫助,將不勝感激。謝謝你的幫助。將字符串轉換爲大寫字母有問題

int main() 
{  

    vector<string> svec, svec_out; 
    string word; 
    int run; 

    cout << "Press 0 to quit giving input string" << endl; 

    while(1) 
    { 
     cin >> word; 
     svec.push_back(word); 

     cin >> run; 
     if (!run) 
      break; 
    } 

    cout << "converting to upper case... " << endl; 

    int i; 
    for (i = 0; i!=svec.size(); ++i) 
    { 
     word = svec[i]; 
     for (string::size_type j=0; j < word.size(); ++j) 
     { 
      toupper(word[j]); 
     } 

     svec_out.push_back(word); 
    } 


    for (i = 0; i<svec_out.size(); i++) 
     cout << svec_out[i] << endl; 

    return 0; 
} 

回答

7

toupper將返回大寫值而不是就地修改值。因此,您的代碼應爲:

word[j] = toupper(word[j]); 
0

好的我得到了問題。錯過TOUPPER()方法的返回值

+0

那麼你應該接受的答案是幫助你(或者這個,如果你是由你自己完成的話)。 – Johnsyweb 2011-03-23 17:18:54

+0

@Johnsyweb:作爲新的stackoverflow我仍然在學習它的功能。感謝您指向我:) – lycon 2011-03-23 17:53:41

+0

你非常歡迎來到StackOverflow! – Johnsyweb 2011-03-23 20:37:50

0

我想你應該在TOUPPER值分配給你的話

word[j] = toupper(word[j]); 

這應該做的。

0

使用std::transform爲:

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <iterator> 
#include <cctype> 

int main() { 
    std::string s="nawaz"; 
    std::string S; 
    std::transform(s.begin(),s.end(), std::back_inserter(S), ::toupper); 
    std::cout << S ; 
} 

輸出:

NAWAZ 

在線演示:http://ideone.com/WtbTI

+0

當您包含時,std名稱空間中的toupper()不是?請注意,它也適合我。我只是在大聲思考。 – 2011-03-23 18:07:19

+0

@Martin:以前我寫過'std :: toupper',但沒有編譯。但是當我刪除了'std ::'時,我驚訝地發現它被編譯了。所以我和你一樣懷疑! – Nawaz 2011-03-23 18:11:28

0
#include <algorithm> 
using namespace std; 
transform(svec[i].begin(), svec[i].end(), svec[i].begin(), toupper); 
1

一個簡單的提示(超過一個答案):調用::與TOUPPER 一個char類型是未定義的行爲(即使大多數的實現試圖在大多數情況下使其工作)。 global :: toupper 函數需要輸入爲int,並且該int必須在 範圍內[0,UCHAR_MAX]或等於EOF(通常爲-1)。如果純字符 char被簽名(最常見的情況),您將最終以負值調用 :: toupper。

+0

+1教給我重要的事情;) – odinthenerd 2014-07-31 13:34:21

0

我申辦的代碼最短位:

#include <boost/algorithm/string.hpp> 

boost::to_upper(svec); 

你可以找到更多的Boost String Algorithm[to_upper][2]就地修改字符串,還設有to_upper_copy表弟,它返回(轉換)複製和葉原始字符串不變。

0

有點過時,但你可以改變:

for (string::size_type j=0; j < word.size(); ++j) 
    { 
     toupper(word[j]); 
    } 

到:

for (auto &j : word) // for every j in word (note j is a reference) 
    j=toupper(j); // replace that j with it's uppercase 

剛剛獲悉,從C++入門這個東西 - 第一部分 - 第3章

相關問題