Printing I love you with cout
Use std::cout and put the text in double quotes:
#include <iostream>
int main() {
std::cout << "I love you" << std::endl;
return 0;
}
The program prints:
I love you
How the program works
#include <iostream>loads the input and output tools, includingstd::cout.int main()is the function where the program starts.std::cout << "I love you"sends the text to the screen.std::endlends the line. Many programmers write"\n"at the end of the text instead, which also ends the line.return 0;tells the operating system the program finished normally.
Each statement ends with a semicolon. Text goes in double quotes. Single quotes are for a single character, so 'I love you' will not print the phrase.
Printing quotation marks
If you want the quotation marks to appear in the output, escape them with a backslash:
std::cout << "\"I love you\"" << std::endl;
The program prints:
"I love you"
Keeping the message in a class
Encapsulation makes this example more interesting. This version stores the message in a private member, so code outside the class can only show it through a public function.
#include <iostream>
#include <string>
class LoveNote {
public:
LoveNote(const std::string& text) : message_(text) {}
void show() const {
std::cout << message_ << std::endl;
}
private:
std::string message_;
};
int main() {
LoveNote note("I love you");
note.show();
// note.message_ = "Hello"; // error: message_ is private
return 0;
}
The program prints I love you. The message is set once, in the constructor. There is no setter, and message_ is private, so the only way to read the message from outside is through show(). The access rules behind private are explained in access modifiers in c.
Common mistakes
- Missing include. Without
#include <iostream>, the compiler reports an error sayingcoutis not a member ofstd. - Missing semicolon. Each statement needs a
;. Leaving one out usually causes a compile error. - Single quotes. Use double quotes for text. Single quotes hold a single character.
Compile and run it
With g++ installed, save the code as love.cpp and run these commands in a terminal:
g++ -std=c++17 love.cpp -o love
./love