How to convert an entire string to uppercase characters without using loop?

Asked

Viewed 53 times

0

I have the following code:

#include <iostream>
#include <ctype.h>
using namespace std;

int main() {
   string nome = "pedro", up;
   
   for (int n = 0 ; n != nome.length(); n++) {
      up += toupper(nome[n]);
   }
   
   cout << "SEJA BEM-VINDO(A), " << up << endl;
   
   return 0;
}

That generates the output:

SEJA BEM-VINDO(A), PEDRO

There is a C++ function that converts a string to uppercase without having to loop through letter by letter using the toupper() to capitalize characters, as done in the above code?

  • Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

1 answer

3

There is nothing ready, you have to write the code, as you did (although it is not a very good idea for efficiency since it changes the size of the string, but that does not affect an exercise, even this is not critical because internally it is treated in a reasonable way, it is just not ideal, and it is possible to eliminate this problem with the proper initialization). If you can touch the original object itself you can also do:

for (auto &letra: nome) letra = toupper(letra);

Documentation and of iterators.

Or

transform(nome.begin(), nome.end(), nome.begin(), ::toupper);

Documentation.

I put in the Github for future reference.

Or the way you find it most convenient to scroll through the text. And you can create a function to use later when you need it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.