将字符串转换为大写字母时出现问题

时间:2011-03-23 16:48:42

标签: c++

使用以下控制台应用程序我将每个字符串转换为大写字母。但输出中的字符串值保持不变。我在这做错了什么。此外,任何有效帮助的帮助将不胜感激。谢谢你的帮助。

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

8 个答案:

答案 0 :(得分:7)

toupper将返回大写值,而不是就地修改值。因此,您的代码应为:

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

答案 1 :(得分:1)

一个简单的提醒(不仅仅是一个答案):调用:: toupper with 类型char是未定义的行为(即使大多数实现 尽量让它在大部分时间都能正常工作。全局:: toupper 函数需要在输入中使用int,并且int必须在 range [0,UCHAR_MAX]或等于EOF(通常为-1)。如果平淡 char签名(最常见的情况),你最终会打电话 ::带有负值的toupper。

答案 2 :(得分:0)

好的,我遇到了问题。错过toupper()方法的返回值

答案 3 :(得分:0)

我认为您应该将toUpper值分配给您的单词

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

应该这样做。

答案 4 :(得分: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

答案 5 :(得分:0)

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

答案 6 :(得分:0)

我竞标最短的代码:

 #include <boost/algorithm/string.hpp>

 boost::to_upper(svec);

您可以在Boost String Algorithm中找到更多内容,[to_upper][2]修改字符串,并且还有一个to_upper_copy表兄弟,它会返回一个(已转换的)副本并保持原始字符串不变。

答案 7 :(得分: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 ++ Primer - 第一部分 - 第3章

学到了这些东西
相关问题