Reputation:
I'm trying to convert every letter in a string to uppercase. I'm looping through each character and using toupper
on it. However, when I print the new string out, it's not working. Sorry if this is a newbie question. Any help would be greatly appreciated :)
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str1, str2;
cin >> str1 >> str2;
int len = str1.size();
for (int i = 0; i < len; i++) {
toupper(str1[i]);
toupper(str2[i]);
cout << str1[i] << " " << str2[i] << endl;
}
}
Upvotes: -1
Views: 4741
Reputation: 7100
In your loop, you don't change the elements of the strings because toupper()
returns a new character, it doesn't change the passed character. You need to make your elements be the same as the returned characters, as follows:
for (int i = 0; i < len; i++) {
str1[i] = toupper(str1[i]);
str2[i] = toupper(str2[i]);
cout << str1[i] << " " << str2[i] << endl;
}
Upvotes: 1
Reputation: 311058
For starters this loop
for (int i = 0; i < len; i++) {
toupper(str1[i]);
toupper(str2[i]);
cout << str1[i] << " " << str2[i] << endl;
}
can invoke undefined behavior because the strings str1
and str2
in general can have different lengths.
These calls
toupper(str1[i]);
toupper(str2[i]);
has no effect because they change neither str1[i]
no str2[i]
.
Also you need to convert the argument of a call of toupper
to the type unsigned char
.
You could separately output each string the following way
for ( unsigned char c : str1 )
{
std::cout << ::toupper( c );
}
std::cout << ' ';
for ( unsigned char c : str2 )
{
std::cout << ::toupper( c );
}
std::cout << '\n';
Upvotes: 0
Reputation: 57728
This may be better, depending on your coding standards:
std::transform(str1.begin(), str1.end(), str1.begin(), std::toupper);
std::transform(str2.begin(), str2.end(), str2.begin(), std::toupper);
The above uses the STL function transform
to convert the string to all uppercase.
Upvotes: 3
Reputation: 763
You need to save the modified strings back into the str arrays. Something like this:
str[i] = toupper(str[i]);
Upvotes: 2
Reputation: 60238
std::toupper
returns a value rather than modifying its argument. So you need to do:
str1[i] = std::toupper(str1[i]);
str2[i] = std::toupper(str2[i]);
in order to actually modify the strings.
If you turn on warnings, e.g with -Wall
the compiler will tell you that your version of the code has no effect.
Upvotes: 4