Why do i use cout<< "a:"; in this program?

#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}

Why can`t i use just cout << a;
and cout << b;
Whats the diference?
Difference is in the output program gives:
a:4 b:7
For the original program.
47
For your change in program

EDIT: Printing a TEXT which tells what variable it prints out makes error hunting more easily :P
Last edited on
You can also output multiple things per line:
cout << "a:" << a << " b:" << b;
Agreed to Branflakes91093!

Forgot to tell that :P
Anything within the quotation marks is a string when you are using it with cout.

Without the quotation marks it takes names of variables and statements or even mathematical operations - (all of this as far as i know anyway, you can even cout a function and c++ will output what it returns) - and outputs the value.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

int someFn(int &variable)
{
    variable = 1;
    return variable;
}

int main()
{
    int variable = 0;
    string stringA = "Meow";
    // cout takes numbers at face value like so:
    cout << "The number is: " << 1 << "." << endl;
    // cout takes a string like the previous posts explained
    cout << "The number is: " << "1" << "." << endl;
    // cout takes mathematical operations like so:
    cout << "The number is: " << 2-1 << "." << endl;
    // more mathematical operations:
    cout << "The number is: " << (1*1) << "." << endl;
    // yet another mathematical operation:
    cout << "The number is: " << 1/1 << "." << endl;
    // cout takes variables and outputs their values,
    // I'll show this here with an integer and a string already declared
    cout << "The integer is: " << variable << "." << endl;
    cout << "The string says: " << stringA << "." << endl;
    // You can even output the return of a function by calling the function within cout !!
    cout << "The result of the function is: " << someFn(variable) << "." << endl;
    cin.get();
    return 0;
}


There are some very creative and fun ways to mess around with cout.

Try copying that code and messing around with it until you understand all these ways you can output with cout. :)
Last edited on
Oh... got it! that was so easy:)
Thx lads.
Last edited on
Topic archived. No new replies allowed.