簡體   English   中英

將字符串轉換為大寫字母時出現問題

[英]Got problem converting string to upper case letters

使用以下控制台應用程序我將每個字符串轉換為大寫字母。 但輸出中的字符串值保持不變。 我在這做錯了什么。 此外,任何有效這方面的幫助將不勝感激。謝謝你的幫助。

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;
}

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

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

一個簡單的提醒(不僅僅是一個答案):使用char類型調用:: toupper是未定義的行為(即使大多數實現嘗試使其在大多數時間都可以工作)。 global :: toupper函數在輸入中需要int,並且int必須在[0,UCHAR_MAX]范圍內或等於EOF(通常為-1)。 如果簽署了普通字符(最常見的情況),您將最終使用負值調用:: toupper。

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

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 ++ Primer - 第一部分 - 第3章學到了這些東西

好的,我遇到了問題。 錯過toupper()方法的返回值

我認為你應該為你的單詞分配toUpper值

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

那應該做。

使用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

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

我競標最短的代碼:

 #include <boost/algorithm/string.hpp>

 boost::to_upper(svec);

你可以在Boost字符串算法中找到更多, [to_upper][2]修改字符串到位,並且還有一個to_upper_copy表兄弟,它返回一個(轉換的)副本並保持原始字符串不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM