noobatcoding
noobatcoding

Reputation: 1

Converting all to uppercase

Hey so I'm very new to c++ and trying to convert a word a user enters to all uppercase

#include<iostream>
#include<cstring>


using namespace std;
int main()
{
  int size=10;
  int i =0;
  char arr[size];
  cout<<"Enter a word"<<endl;
  cin.get(arr,size);

  for(i = 0; i < 10; i++)
  {
    if(islower(arr[i]))
    {
      cout<<toupper(arr[i])<<endl;
    }
  }
  return 0;
}

I'm getting numbers when I run this. What do I fix?

Upvotes: 0

Views: 212

Answers (2)

CroCo
CroCo

Reputation: 5741

It is the time to learn one of bit-wise applications

#include <iostream>
#include <string>

int main()
{
    int mask = 0xDF;
    std::string str = "aBcdeqDsi";

    for(int i(0); i < str.size(); ++i)
        std::cout << static_cast<char>(str[i] & mask);

    std::cout << std::endl;

    return 0;
}

Upvotes: 0

Rietty
Rietty

Reputation: 1156

Don't write C-like C++, use the standard library to your advantage. Use an std::string and do something like this instead:

#include <iostream>
#include <algorithm> 
#include <string>  

int main() {
    std::string input;
    std::cin >> input;
    std::transform(input.begin(), input.end(), input.begin(), ::toupper);
    std::cout << input << std::endl;
    return 0;
}

Or alternatively with a lambda:

std::transform(input.begin(), input.end(), input.begin(), [](unsigned char c){ return std::toupper(c); });

Upvotes: 5

Related Questions