-2

Output is same as the input where am i making the mistake? Pls check the test version, it prints the ASCII code of 'A' but not A why is it so?

The 1st if condition in the loop is to make sure that the string starts with a valid character only and not space.

void caps(char* p)
{
   char* begin=NULL;
   char* temp=p;

    while(*temp)
    {

      if((begin == NULL) && (*temp!= ' '))
        begin=temp;

      if(begin && ((*(temp+1) == ' ' ) || (*(temp+1)=='\0')))
      {
         toupper(*temp);
         begin=NULL;
      }

         temp++;
    }

 cout<<p;
}


int main()
{
  char str[]={"i like programming"};
  cout<< str <<endl;
  caps(str);
  return 0;
}

Test

If I use printf("%c",toupper(a)) it prints 'A' correctly.

#include <iostream>
#include <ctype.h>

using namespace std; 

int main()
{
   char a= 'a';
   cout<<toupper(a); //prints ASCII code of A(65) but why not 'A' ?
   return 0;
}
Stack
  • 235
  • 3
  • 15
  • 1
    From the above link: it is deliberately returned as an `int`, you can simply cast the return of `toupper` back to a `char` and it will work as you intended. – Cory Kramer Apr 22 '15 at 11:39
  • ok it works in the second case, but how do i make it work in the first case? – Stack Apr 22 '15 at 11:43
  • You are doing `toupper(*temp);` You should be doing `*temp = toupper(*temp);`, as the `toupper` function does not use a reference, and thus can't automatically change `*temp`. – Lighthink Apr 22 '15 at 11:48
  • Also, the title of this question states that you need the first character uppercase'd. Your code looks like it is changing the last character of a word. You should convert to uppercase in the same spot where you do `begin = temp`. – Lighthink Apr 22 '15 at 11:52
  • There is a mistake in the code it does change the last char of the word. I am trying to fix that – Stack Apr 22 '15 at 11:55

1 Answers1

-3

Well, in the first code cout << str << endl; str is a pointer(it's type is char*). To output the first character of str, use cout << str[0]; or cout << *str;. And toupper() returns int, not char, so you need to cast the result:

cout << (char)toupper(a);
thefunkyjunky
  • 492
  • 4
  • 15