Creeper Creeper - 3 months ago 16
C++ Question

Output spaces in C++?

i'm currently new to C++ and the whole programming thing and i have no prior knowledge of any programming language except C, which i'm still learning. I bought an E-book on amazon to learn C++ and i'm currently practicing some of the examples from the book on Dev C++ on Windows. I'm trying to output a space in between numbers from this simple code but i have no idea D:

#include <iostream>

using namespace std;
int main()
{
int x;
for (x=0; x<=5; x++)
{
cout << x;
}
}


so, when i execute the above code, i get the output 012345. How do you add spaces in between the numbers so the output looks like this 0 1 2 3 4 5?

tried

cout << x << endl;


but it output results on the next line, i'm trying to output spaces in between the numbers. i tried \ backslash to add an escaping character

cout << x\t;


but i get an error [Error] ";" expected before 't'. So, what code should i type to output the spaces? Thanks!

Answer
#include <iostream>

using namespace std;
int main()
{
    int x;
    for (x=0; x<=5; x++)
    {
    cout << x << " ";  // Add a trailing whitespace
    }
}
Comments