unexpected output

hi guys just wondering why that when I go through the loop it prints HELLO in chars

But when I call this statement cout << toupper(hello[0]); it prints out an int 72 instead of a capital char??

I'm so confused as to why this is,why does this happen? and why does the for loop not print out numbers if thats the case?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
#include <string>
using namespace std;

int main()
{

   string hello;
   hello = "hello";
   for(int x = 0;x < hello.size();x++){

       hello[x] = toupper(hello[x]);

   }
   cout << hello << endl;
   cout << toupper(hello[0]);
}
Last edited on
That's because toupper returns an int.
http://www.cplusplus.com/reference/cctype/toupper/?kw=toupper

Cast it to a char and you will be fine.

why does the for loop not print out numbers if thats the case?

Your assignment statement at line 12 is implicitly casting the int result of toupper to a char.



ah ok so I would just put (char) infront of it to cast to a char

but at line 12 how did I cast the int to a char?


also AA I'm just wondering could I learn how to program in c++ well without reading a book(just using the internet) or do you reccomend getting a book to follow?
Last edited on
but at line 12 how did I cast the int to a char?

You didn't. The compiler did.

Note that I said "implicitly" above, meaning that an explicit cast wasn't necessary (although recommended).

You should have received a compiler warning on line 12 regarding possible truncation when assigning an int to a char.

do you recommend getting a book to follow?

It all depends on your style of learning. The tutorials here are very good. A good book such as http://rads.stackoverflow.com/amzn/click/0321992784 by Bjarne Stroustrup is indispensible as a reference.
thanks

I completed buckys c++ tutorials,just learned about iterators,vectors,files I just don't know where to go from there,my goal is to be able to write desktop applications and computer viruses for fun obviously as I find it cool that you can control a computer,where do you reccomend I go from here? learning wise
Last edited on
Topic archived. No new replies allowed.