trying to change first letter of each name to upper case.

I can get the first letter to change if there is only one word.
But if there are two words it wont change and display the second word's first letter and I'm not sure why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cctype>
#include <string>
#include <array>
using namespace std;

int main()
{
	char ans;
	string stateName;

	do
	{
		getline(cin, stateName);

		int sp1 = stateName.find(' ');
		int sp2 = stateName.find(' ', sp1 +1);

		if(sp1 = -1)
		{
			stateName[0] = toupper(stateName[0]);
			cout << stateName << " or " << stateName[0];
		}
		else if(sp2 == -1)
		{
			int len = stateName.length();
			string secondName = stateName.substr(sp1+1, len - sp1-1);
			stateName[0] = toupper(stateName[0]);
			secondName[0] = toupper(secondName[0]);
			cout << stateName << " or " << stateName[0] << secondName[0];
			cout << endl;
		}


		cout << "Continue(y/n)? ";
		cin >> ans;
	}while(toupper(ans) == 'Y');

	return 0;
}

if(sp1 = -1) should be if(sp1 == -1)
not sure if this is what you are looking for
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cctype>
#include <string>
#include <array>
using namespace std;

int main()
{
	char ans;
	string stateName;
	int sp1;
	do
	{
		cout << "Please enter a name: ";
		getline(cin, stateName);
		cout << endl;

		sp1 = stateName.find(' ');

		if(sp1 == -1)
		{
			stateName[0] = toupper(stateName[0]);
			cout << stateName << " or " << stateName[0] << endl;
		}
		else
		{
			stateName[0] = toupper(stateName[0]);
			stateName[sp1 + 1] = toupper(stateName[sp1 + 1]);
			cout << stateName << " or " << stateName[0] << stateName[sp1 + 1];
			cout << endl;
		}


		cout << "Continue(y/n)? ";
		cin >> ans;
		ans = toupper(ans);
		cin.ignore();

	}while(ans == 'Y');

	return 0;
}
Last edited on
Yep! that actually was all I needed to do.

Now my do while loop is giving me an error, String subscript out of range.

I've been trying to fix it for the past 15 minutes but I can't figure it out.

EDIT: just saw that you added the cin.ignore(). That fixed the problem, thanks for the help!
Last edited on
std::string::find is defined to return std::string::npos if no match is found.

http://www.cplusplus.com/reference/string/string/find/

Return Value
The position of the first character of the first match.
If no matches were found, the function returns string::npos.

size_t is an unsigned integral type.

You should test against npos, not -1. The actual value of npos is std::string's business, not yours!

1
2
3
if(sp1 == string::npos)
{
    // etc 


or

1
2
3
if(sp1 == sp1.npos)
{
    // etc 


Andy
Last edited on
Topic archived. No new replies allowed.