简体   繁体   中英

Unexpected output in VERY basic C++ program

EDIT: My last question is how do I get a space before the number I put and then put a . at the end of the sentence?

Original Question:

I am learning C++. This is my code

#include <iostream>

int main() {
    int iNum;
    std::cout << "Please enter your favorite number" << std::endl;
    std::cin >> iNum;
    std::cout << "Your favorite number is" << std::cout << iNum << std::endl;
    return 0;
}

I removed the spaces to make it easier to read. I expect the output to be Your favorite number is 4 if I were to enter a 4 when asked. Instead it says, Your favorite number is51ABC3E84. The last number will always be whatever number I pick. What am I messing up to get the weird output? Thanks for the help for a very noob programmer.

Remove the second std::cout after you retrieved input, that serves no purpose in your program.

The corrected line should be: (updated to reflect updated parts of question)

std::cout << "Your favorite number is " << iNum << "." << std::endl;

When you send std::cout into the stream, you're actually having the std::cout object try to process itself as something to be printed. In this case, it seems to be interpreting it as a 32-bit value (probably the memory location of std::cout ) represented in hex. The "4" at the end of "51ABC3E8" in your output is the value of the variable taken from input.

 std::cout << "Your favorite number is" << std::cout << iNum << std::endl;
                                        //^^You are printing cout

should be

std::cout << "Your favorite number is"  << iNum << std::endl;

You only need to say std::cout once. After the initial cout , you just chain all the output you want with << until the statement ends in a ; . When you put it behind << as in your code, you're actually printing cout as converted to a void* .

std::cout << "Your favorite number is" << iNum << std::endl; ought to do the trick for you.

EDIT: If you want a space and period, just put them in your output line:

std::cout << "Your favorite number is " << iNum << '.' << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM