C++ while 述句的問題



#include "stdlib.h"

#include <iostream>

//#include "Sales_item.h"

int main()


using namespace std;

int value,sum=0;

cout<<"Please enter series number:";





cout<<"The sum is "<<sum;


return 0;


為何所輸入的數字 3 4 5 6



4 Answers

  • 1 decade ago
    Favorite Answer


    This question pointed out a big problem in learning C++: most students use a class before they really understand it. As matter of fact, even many graduate students cannot understand this problem. Here is the problem:

    while (cin >> value) {}

    (1) do you read the declaration of the istream and how it overload operator>> ?

    The declaration for int value argument is:

    istream& operator>> (int & val);

    from here, you should know that the expression

    cin >> value

    is evaluated to

    (istream&) cin, which is always != FALSE

    This means that your while loop is an infinite loop!!!

    That was why your statement

    cout << "xxx" << sum;

    is never evaluated, thus there is no output.

    My question to you:

    Why does C++ brings back the abstract data type "reference" as in FORTRAN? Shouldn't "pointer" be enough, like in C?

    2009-07-07 01:25:50 補充:

    Oh, if 上帝 only wants to know the answer to his question, here it is:

    while (!cin.eof() && cin >> value) { sum+=value}

    Now, where is mine?

    2009-07-09 07:04:20 補充:

    Also, I think it is better to move "cin >> value" out fo the (). So, it should be:

    while(!cin.eof()) {cin >> value; sum += value;}

    • Login to reply the answers
  • 1 decade ago

    請輸入 3 4 5 6 完後 ,輸入q

    • Login to reply the answers
  • 鳳綾
    Lv 4
    1 decade ago

    因為你沒用 Ctrl+Z 結束輸入啊..

    • Login to reply the answers
  • 昌興
    Lv 7
    1 decade ago

    cin進去的是文字, 還要將它轉為數字, 才能作加減

    • Login to reply the answers
Still have questions? Get your answers by asking now.