C++ “||”之前应为主表达式

C++ “||”之前应为主表达式,c++,C++,新手在这里胡闹,我遇到了这个错误:在“| |”标记之前应该是主表达式。检查过我能找到的类似问题的帖子,但没有运气。 非常感谢您的帮助 #include <iostream> #include <string> using namespace std; int main() { string txt; while(txt == "") || (txt == " "); { cout << "Please enter the sentence

新手在这里胡闹,我遇到了这个错误:在“| |”标记之前应该是主表达式。检查过我能找到的类似问题的帖子,但没有运气。 非常感谢您的帮助

#include <iostream>
#include <string>
using namespace std;

int main()
{

 string txt;

 while(txt == "") || (txt == " ");
 {
     cout << "Please enter the sentence you want to translate.";
     cin >> txt;
 }
}
while的语法大致如下:

while(condition)
    block
其中,block是一条语句或包含在{and}中的多条语句

条件后面没有分号,需要将条件用括号括起来


我建议你从C++学习。你的教学材料应该向你解释语法结构的语法,你不应该试图猜测它。

试着用括号括住整个while条件:

while ((txt == "") || (txt == " ")) {
    ...
}

从编译器获得此错误消息的原因是,它看到了| |运算符,并希望找到两个主表达式,在| |的每一侧各一个。在您的例子中,whileText==不是主表达式

从中,主表达式是:

100 // literal
'c' // literal
this // in a member function, a pointer to the class instance
::func // a global function
::operator + // a global operator function
::A::B // a global qualified name
( i + 1 ) // a parenthesized expression
这可能会让人困惑,因为编译器对代码的看法与您不同,而且即使在您看来显而易见的情况下,也很难理解您试图编写的代码

您试图做的是,编写一个while循环,在C中的拼写如下++

whilecondition 陈述 //或 whilecondition { 声明。。。 } 条件可以是一个类似于您使用的复合表达式

whileText==| txt== { cout>txt; }
与python不同,while和if等关键字后面的条件语句必须完全括在括号中。注意:对于std::string,>>运算符通常会在找到空白后立即停止并返回它收集的内容。这意味着cin>>txt;会读一个单词,而不是一个句子。很可能是这里最好的工具。非常感谢您的快速回复。真不敢相信我在这么简单的事情上浪费了多少时间mistake@panos请参阅我的编辑。如果你还没有,那就用一本教你正确语法的好书。我不知道你是怎么想到在条件后面应该有一个分号,或者不需要用括号括起来。