C++ input output

时间:2018-02-03 10:09:46

标签: c++ c++11

I saw two codes and was wondering why one should work and the other not....thanks in advance..

I know it's a really simple question but thanks for your time

#include <iostream>
using namespace std;
#include <cstring>
const int STR_LIM = 50;
int main()
{

char word[STR_LIM];
cout << "Enter word, to stop; press the word done" << endl;
int Count = 0;

while (cin >> word && strcmp("done", word))
    ++ Count;
cout << "You entered a total of " << Count << " words. \n";


return 0;
}

And:

#include <iostream>
using namespace std;

int main()
{
int i = 0;
char word[256];

while(cin >> word != "done")
    ++i;

cout << i;

}

2 个答案:

答案 0 :(得分:0)

Becuase cin>>word returns ostream object and it is not comparable with Strings!

答案 1 :(得分:0)

Why does

while(cin >> word != "done") ++i;

not work?

At first, the operator precedences have to be checked e.g. C++ Operator Precedence to find the order of evaluation. So, >> binds stronger than !=. Hence, the above code is identical with

while((cin >> word) != "done") ++i;

Next, the types of operators/expressions have to be analyzed:

(cin >> word) is std::istream& × char*std::istream&

according to e.g. cppreference.com.

Hence,

((cin >> word) != "done") is std::istream& × const char[5]

which may decay to std::istream& × const char*.

There is no bool operator!=(std::istream&, const char*) available.

Hence, it does not compile.

Life demo on ideone

prog.cpp: In function ‘int main()’:
prog.cpp:10:25: error: no match for ‘operator!=’ (operand types are ‘std::basic_istream<char>’ and ‘const char [5]’)
       while(cin >> word != "done")  ++i;
             ~~~~~~~~~~~~^~~~~~~~~

Without the abbreviation it should:

while(cin >> word && strcmp(word, "done")) ++i;

Using std::string word; instead of char word[256]; it can be written even more intuitive as

while(cin >> word && word != "done") ++i;

because std::string provides suitable operator!=()s for this.

Life demo on ideone.