-3

I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

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

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";  
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }

I get the output as:

HELLO WORLDHello World

But the required output is:

HELLO WORLD HELLO WORLD

How do I make the

 cout<<str; 

statement in main() to print the result computed in the function :

 void stringToUpper(string &s)
Aanandhi V B
  • 79
  • 2
  • 10

3 Answers3

0

Solution only for the lower part of ASCII characters.

class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      if (s[i] > 96 && s[i] < 123)
        s[i] -= 32;
    }
  }
};

and if you care about the higher part of the ASCII table:

class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      s[i] = toupper(s[i]);
    }
  }
};

If you have some multi-byte encoding, like UTF-8, you will need some library.

Yuki
  • 3,857
  • 5
  • 25
  • 43
0

cout << str; //This line should not be changed

This means that you must change str.

void stringToUpper(string &s) //This line should not be changed

Good news, your method take s as a reference.

In your code you are doing c=s[i]; you should reassign the char in your string s[i] = c

jbalestr42
  • 74
  • 1
  • 6
0

You are just printing the string with making each character as upper character, but the string that passed to function (by reference) "s" does not get changed.

void stringToUpper(string &s)

A line can be added to make s to get changed in void stringToUpper(string &s)

 s[i] = toupper(c);

Code will look

 c=s[i];
 s[i] = toupper(c);
 putchar (toupper(c));
 i++;

Output will be

HELLO WORLDHELLO WORLD
raj
  • 63
  • 1
  • 7