Missing text

More basic practicing codes I'm afraid. I've made a little thing to double a number designated by the user but the actual text that should be showing (apart from "Enter x value: ") isn't appearing. I'm just getting "Enter x value: ", then when I input 5 I get 10 back on the next line. Any thoughts?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>

int doubleNumber(int x)
{
    using namespace std;
    cout << "Enter x value to be doubled: " << endl;
    int x;
    cin >> x;
    return x * 2;
}

int main()
{
    using namespace std;
    int x = -1;
    cout << "Double x is: " doubleNumber(x) << endl;
    return 0;
}
Last edited on
closed account (EwCjE3v7)
You have a few errors above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int doubleNumber() // take useless int x away
{
    using namespace std;
    cout << "Enter x value to be doubled: " << endl;
    int x;         // if we had the variable x above, then this would be in error
    cin >> x;
    return x * 2;
}

int main()
{
    using namespace std; // u may wanna define this in the global scope
    // useless int, can be removed
    cout << "Double x is: " << doubleNumber() << endl; // You forgot the '<<' operator in the middle.
    return 0;
}


C++ Shell: http://cpp.sh/32t

Many useless stuff up there, I have removed them and also you missed a '<<' operator.
Thanks very much for the help, what do you mean by global scope? (I'm still very new to coding)
Global scope means visible to the entire translation unit. As you have it, using namespace std; is only visible within your functions. By putting it at line 2, you don't need to include it within each function.

Ah that makes sense, thanks again!
You might also have done this, to make use of the x declared in main() by passing it as a parameter to the function. Note that the variable name used doesn't have to be the same in function doubleNumber() as in main()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;
    
int doubleNumber(int n)
{   
    return n * 2;
}

int main()
{
    int x = 0;
    cout << "Enter x value to be doubled: " << endl;
    cin >> x;
    cout << "Double x is: " << doubleNumber(x) << endl;
    return 0;
}
Topic archived. No new replies allowed.