convert uppercase from a string

I'm new to c++ and i have an assignment that's need to be done.
i need a to convert the word "by" to upper case. below is what i've gotten so far but i cant seem to get the result.

#include <iostream>
#include <cctype>
#include <string>
using namespace std;

int main()
{
string inStr("Twelve Songs by Christmas");
cout << "\n inStr before function call = " << inStr << endl;

for (int i=0; i < inStr.length(); i++)
{
if((inStr.at(i) == ' ') && (inStr.at(i) == 'b') && (inStr.at(i) == 'y') && (inStr.at(i) == ' '))
inStr.at(i)=toupper(inStr.at(i));
}

cout << "\n inStr after function call = " << inStr << endl;
system("pause");
return 0;
}
Please use [code][/code] tags.

Your if statement inside the for loop will never be true; it checks to see if character i in your string is a 'b', a 'y', and a space all at the same time, which can never happen.
If you are using std::string class then it would be better if you use its methods as, for example, find() to find literal "by" or " by " in your string.
thanx for the info. other than find(), is it still possible to use an 'if' statement?
Using an if statement is certainly viable.

I would suggest changing i<inStr.length() to i<inStr.length()-1 as you're looking for a substring that is of length 2.

Within the for loop, I would first check inStr[i] to see if it's 'b' and then check inStr[i+1] to see if it's 'y'. If both are true, then replace them both. If you use the current if statement (assuming you converted the &&'s to ||'s) you would be replacing all occurrences of 'b' and 'y' in the string which is probably not what you want. Even if you follow the advice I give you here, you will still have a problem with words containing the sequence "by".

(inStr.at(i) == ' ') && (inStr.at(i) == 'b') && (inStr.at(i) == 'y') && (inStr.at(i) == ' ')
this condition never occurs
btw, i tried to make some test, but i got an awkward result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
using namespace std;

int main () {
	std::string some_name = "some name";
	for (int i = 0; i < (some_name.size() - 1); ++i) {
		char some_char = some_name[i];
		cout << toupper (some_char);
	}
	cout << endl;
	cin.get();
	return 0;
}


and shown:

8379776932786577

why is that?
nevermind i got it...

btw, why you don't use this?

1
2
3
4
5
6

cout << "\n inStr after function call = ";

for (int i=0; i < (inStr.length() - 1); i++)
	cout << (char) toupper(inStr[i]);
cout << endl;
Last edited on
Topic archived. No new replies allowed.