Using following console application i am converting each string to uppercase letters. But string value in output remains unchanged. what I am doing wrong here. Also any help on doing this efficiently would be appreciated.Thanks for your help.
int main()
{
vector&开发者_运维问答lt;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
will return the uppercase value instead of modifying the value in-place. As such your code should read:
word[j] = toupper(word[j]);
A simple reminder (more than an answer): calling ::toupper with a type char is undefined behavior (even if most implementations try to make it work most of the time). The global ::toupper function requires an int in input, and that int must be in the range [0, UCHAR_MAX] or be equal to EOF (usually -1). If plain char is signed (the most frequent case), you will end up calling ::toupper with negative values.
Ok I got the problem. miss the toupper() method's return value
I think you should assign the toUpper value to your word
word[j] = toupper(word[j]);
That should do.
#include <algorithm>
using namespace std;
transform(svec[i].begin(), svec[i].end(), svec[i].begin(), toupper);
Use std::transform
as:
#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 ;
}
Output:
NAWAZ
Online demo: http://ideone.com/WtbTI
I bid for the shortest bit of code:
#include <boost/algorithm/string.hpp>
boost::to_upper(svec);
You can find many more in Boost String Algorithm, [to_upper][2]
modifies the string in place and also features a to_upper_copy
cousin, which returns a (transformed) copy and leaves the original string untouched.
kinda outdated but you can change:
for (string::size_type j=0; j < word.size(); ++j)
{
toupper(word[j]);
}
to:
for (auto &j : word) // for every j in word (note j is a reference)
j=toupper(j); // replace that j with it's uppercase
Just learned this stuff from C++ Primer - Part I - chapter 3
精彩评论