Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++ cin within funtions?

void test(int a){

cin >> a;

}

int main () {

int number;

test(number);

cout << number;

return 0;

}

Why dosen't number take on the value of a? What other ways can I get user input within a funtion?

Thanks =)

2 Answers

Relevance
  • ?
    Lv 7
    10 years ago
    Favorite Answer

    Because a was passed to test() by value. Changes made to test()'s a have no effect on main()'s numer.

    You could either use pass-by-reference:

    void test(int& a){

         cin >> a;

    }

    or return the value

    int test()

    {

         int a;

         cin >> a;

         return a;

    }

    int main()

    {

         int number = test();

         cout << number;

    }

  • cja
    Lv 7
    10 years ago

    test's argument a is passed by value, so whatever you do to this argument inside the function does not change the actual parameter.

    Try this:

        void test(int &a) {

            cin >> a;

        }

    Another option is :

        int test( ) {

            int a;

            cin >> a;

            return a;

        }

    This is very simplistic, of course, not necessarily the best design or implementation.

    EDIT: whoa ... while I was typing in my answer, Cubbi was entering his ... and they're almost identical, reassuring me that my answer is good :-)

Still have questions? Get your answers by asking now.