C++ C++;输入输出

C++ C++;输入输出,c++,c++11,C++,C++11,我看到两个代码,想知道为什么一个应该工作,另一个不工作…提前谢谢 我知道这是一个非常简单的问题,但谢谢你的时间 #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" <<

我看到两个代码,想知道为什么一个应该工作,另一个不工作…提前谢谢

我知道这是一个非常简单的问题,但谢谢你的时间

#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;
}
#包括
使用名称空间std;
#包括
常数int STR_LIM=50;
int main()
{
字符字[STR_LIM];
cout单词和strcmp(“完成”,单词))
++计数;

cout因为word
返回ostream对象,它与字符串不可比较!

为什么

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

首先,必须检查操作员的先例,例如查找求值顺序。因此,
>
绑定比
!=
强。因此,上述代码与

while((cin >> word) != "done") ++i;
接下来,必须分析运算符/表达式的类型:

(cin>>word)
std::istream&
×
char*
→ <代码>标准::istream&

根据例如

因此,

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

它可能会衰减为
std::istream&
×
const char*

没有可用的
bool操作符!=(std::istream&,const char*)

因此,它不会编译

生活演示

prog.cpp:在函数“int main()”中:
程序cpp:10:25:错误:与“operator!=”不匹配(操作数类型为“std::basic_istream”和“const char[5]”)
而(cin>>word!=“完成”)++i;
~~~~~~~~~~~~^~~~~~~~~

如果没有缩写,则应:

while(cin >> word && strcmp(word, "done")) ++i;
使用
std::string word;
而不是
char word[256];
可以更直观地编写

while(cin >> word && word != "done") ++i;
因为
std::string
为此提供了合适的
操作符!=()
s


生活演示开始。

你所说的“工作”是什么意思?请提供预期和实际的行为。我不认为cin>>这个词可以像你在第二个例子中所做的那样直接与字符串“完成”相比较。你在第一个例子中所做的-通过实际阅读输入并使用strcmp似乎是正确的方法。
while(cin >> word && word != "done") ++i;