2011-03-23 162 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章

相关问题