uppercase

i am not able to identify the error in this program...i am trying to make first letter of each word capital..
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
#include<iostream>
#include<conio.h>
#include<string>
//#include<sstream>
using namespace std;
string uppercase(string name)
{
    if((int)name[0]>=97 && (int)name[0]<=122)
        name[0]=char((int)name[0]-32);
int i=0;
while(name[i]!='\0')
{
    if(name[i]==' ')
    {
        name[i+1]=char((int)name[i+1]-32);
    }
i++;
}

}
int main()
{
    string name;
    cout<<"enter name";
    getline(cin,name);
    name=uppercase(name);
    cout<<name;
    getch();
}
There are a couple of errors.
Firstly, uppercase should return a value.
Add return name in line 19.

The run time error it gives is string subscript out of range. It means that the program is trying to access a string character using the [] operator that doesn't exist.

Like if I create a string of 10 alphabets, and then try to access string[100], it will return this error.

EDIT 1:
You don't need to cast the (int)name[0]-32 to char on line 15 & 9.
it will make it a char itself when it is put in name.

EDIT 2;
The error occurs in line 15, when i becomes equal to the last character in the string (say 15), the program tries to access name[16] which doesn't exist.

EDIT 3:
A few tips first:
You can use the for loop instead of while.
for loops use the following format:
1
2
3
4
for (int /*some variable*/ = /*some value*/; /*condition*/; /*increment*/)
{
    /*Loop content*/
}


and finally the corrected code[I have only changed the code to make it work.]:
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
#include<iostream>
#include<conio.h>
#include<string>
//#include<sstream>

using namespace std;

string uppercase(string name)
{
    if((int)name[0]>=97 && (int)name[0]<=122)
        name[0]=char((int)name[0]-32);
int i=0;
while(i != name.size())
{
    if(name[i]==' ' && i != (name.size()-2))
    {
        name[i+1]=char((int)name[i+1]-32);
    }
i++;
}
return name;
}
int main()
{
    string name;
    cout<<"enter name";
    getline(cin,name);
    name=uppercase(name);
    cout<<name;
    getch();
}



And finally, it would seem better to at least capitalize the first word in enter name and adding a space after it.

EDIT 4:
I forgot to mention this:
you can use the cctype library (ctype.h in older versions). It has a function toupper
It can convert a character to uppercase directly. You have to make it equal to the original just as you did in line 26 with this function!

Though It does not return a string, you can use if in lines 9 and 15 to make the code cleaner!
Last edited on
Topic archived. No new replies allowed.