Cannot change a sentence to capital letters

140 views Asked by At

Why doesn't the following program change a sentence to uppercase?

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

 int main()
 {
     char name[20];
     cout << "what is your name?" << endl;
     system("pause");
     cin.get(name, 20);
     name[20] = toupper(name[20]);
     cout << "Your name is " << name<< endl;
     system("pause");
 }
4

There are 4 answers

0
Thomas Matthews On

To change a string to upper case, you can use std::transform:

std::string test_string = "this is a test";
std::cout << "Before modifications: " << test_string << "\n";
std::transform(test_string.begin(), test_string.end(),
               test_string.end(),
               std::toupper);
std::cout << "After modifications: " << test_string << "\n";
2
Ahmad Khan On

You have to convert each character to upper-case, name[20] only gets the index 20 (which, in your case is an invalid index too).

You can loop through the array to convert each character to upper-case.

for (int i = 0; name[i] != '\0'; i++){
    name[i] = toupper(name[i]);
}

You should also see this thread: Why is "using namespace std" considered bad practice?

0
Raindrop7 On

toupper doesn't take a const character string but it only takes a single character as an integer.

Also there's a UB in your code trying to read outbound of the array:

name[20] = toupper(name[20]);

Because as you know arrays are indexed from 0 to n-1 not from 1 through n. Also even if you write it correct:

name[19] = toupper(name[19]);

The line above only converts the character 20th (index 19) to uppercase. And this is not what you wanted; you wanted to convert all the characters to uppercase.

So here is an example:

 char name[20];
 cout << "what is your name?" << endl;
 std::cin.get(name, 20);
 //  name[20] = toupper(name[20]); UB 


 for(int i(0); i < strlen(name); i++) // use strlen instead of specifying the length at compile-time
     name[i] = toupper(name[i]);
 std::cout << "Your name is " << name<< std::endl;


 std::cin.sync(); // only for flushing the input buffer.
 std::cout << "Enter name again: \n";
 std::string strName;
 std::getline(std::cin, strName);

 for(int i = 0; i < strName.length(); i++)
     strName[i] = toupper(strName[i]);

 std::cout << "name: " << strName << std::endl;
  • Use class string it is better that to get stuck to arrays of characters, It's flexible and well designed and don't matter about size...
1
sinduja sindu On
#include <iostream>
#include <string>
using namespace std;
int main(){
char name[20];
cout << "what is your name?" << endl;
system("pause");
cin.get(name, 20);
for(int i=0;i<20;i++){
name[i]=toupper(name[i]);
}
cout << "Your name is " << name<< endl;
system("pause");

}