user3371154
user3371154

Reputation: 17

How would I capitalize every letter of a name from an array in c++?

When I try to compile my program says this" cannot convert âstd::stringâ to âintâ for argument â1â to âint toupper(int)â"

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

int main(){
  string names[10];

  for (int i=0;i<=9;i++){
    cout<<"Please enter name for student "<<i+1<<": ";
    cin>>names[i];
    }

for(int j=0;j<=9;j++){
names[j]=toupper(names[j]);
cout<<names[j]<<endl;
}


return 0;
}

Upvotes: 0

Views: 458

Answers (5)

Netherwire
Netherwire

Reputation: 2787

toupper(int) accepts only one letter, not the whole string. To capitalize whole string, you should write a function such as:

void ToUpperString(std::string& str)
{
    for(int i = 0; i < str.length(); ++i)
    {
        str[i] = toupper(str[i]);
    }
}

And then call it for each string that you want to capitalize:

for(int j = 0; j <= 9; j++)
{
    ToUpperString(names[j]);
}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

Change this loop

for(int j=0;j<=9;j++){
names[j]=toupper(names[j]);

to

for (int j = 0; j < 10; j++ ) names[j][0] = toupper( names[j][0] );

In your loop names[j] returns an element of the array that is an object of type std::string while you need to gett access only to the first character of the object.

You could do the same the following way using the range-based for statement

for ( std::string &s : names ) s[0] = toupper( s[0] );

Upvotes: 0

Mustafa Chelik
Mustafa Chelik

Reputation: 2184

By the way, you can use strupr function:

char str[] = "sample text";
strupr( str );
cout << str; // will print SAMPLE TEXT

Upvotes: 0

masoud
masoud

Reputation: 56509

You must pass a char to std::toupper not whole string:

for (auto &x : names)
  std::transform(x.begin(), x.end(), x.begin(), ::toupper);

Upvotes: 2

yizzlez
yizzlez

Reputation: 8805

std::toupper() takes an int, but you are passing it a string. Do something like this:

for(int j=0;j<=9;j++){
    for(int p = 0; p < names[j].length(); ++p){
        names[j][p]=toupper(names[j][p]);
    }
    cout<<names[j]<<endl;
}

Upvotes: 0

Related Questions