0

How could I use cin to insert values for the function?

cin >> addNumber();
cout << addNumber() << endl;

I am not sure if I used these lines above properly. What command/word or whatever it is called should I use to be able to do so? I'm trying to add a value for the variables x and y to add those two numbers and print the sum.

#include <iostream>

using namespace std;

int addNumber(int x, int y)
{
    int answer = x + y;
    return answer;
}

int main()
{   
    cin >> addNumber();
    cout << addNumber() << endl;
    return 0;
}
Felix Glas
  • 15,065
  • 7
  • 53
  • 82
Dave Martinez
  • 122
  • 2
  • 8
  • 1
    _'I am not sure if I used these lines above properly.'_ No they arent, unless `addNumber()` returns a valid reference to some object that can be accessed by `operator>>(istream&,...)` – πάντα ῥεῖ May 03 '14 at 10:55

2 Answers2

3
#include <iostream>

int addNumber(int x, int y)
{
    int answer = x + y;
    return answer;
}

int main()
{
    int x,y;
    std::cin >> x >> y;

    std::cout << addNumber(x,y) << std::endl;

    return 0;
}
tommyo
  • 531
  • 4
  • 10
khajvah
  • 4,889
  • 9
  • 41
  • 63
  • Thanks, but what does "std::" means and how it is used? I've tried the code. endl seems to cause errors, why is that? It's working if I remove it. `std::cout << addNumber(x,y) << endl;` – Dave Martinez May 03 '14 at 11:00
  • @Rakken yes sorry, I updated the answer. cout, endl, cin are part of namespace `std`, so you have to put `std::` in front or you can put `using namespace std` at the beginning of the file, though it is not a good practice. – khajvah May 03 '14 at 11:04
  • That worked. One more question, you seem to have used std::cout instead of simply cout. Why is that? Can't I just simply use cout and cin rather than std::cout, std::cin? – Dave Martinez May 03 '14 at 11:10
  • If you put `using namespace std` in front of the file, you can use cin and cout without `std::` but it's better practice to use `std::`. take a look at [this](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – khajvah May 03 '14 at 11:32
0
#include <iostream>

using namespace std;

int addNumber(int x, int y)
{
    int answer = x + y;
    return answer;
}

int main()
{   
    int x,y;
    cout<<"Enter first number"<<endl;
    cin>>x;
    cout<<"Enter second number"<<endl;
    cin>>y;    
    cout<<addNumber(x,y)<<endl;
    return 0;
}
Taimour
  • 459
  • 5
  • 21