【问题标题】:C++ endl with constants带有常量的 C++ endl
【发布时间】:2011-10-03 03:07:42
【问题描述】:

我只是想让自己熟悉从 Java 迁移而来的 C++ 基础知识。我刚写了这个功能禁欲程序,遇到了一个错误test.cpp:15: error: expected primary-expression before ‘<<’ token,我不知道为什么。

有人愿意解释为什么endl 不能使用常量吗?代码如下。

//Includes to provide functionality.
#include <iostream>

//Uses the standard namespace.
using namespace std;

//Define constants.
#define STRING "C++ is working on this machine usig the GCC/G++ compiler";

//Main function.
int main()
{
  string enteredString;

  cout << STRING << endl;
  cout << "Please enter a String:" << endl;
  cin >> enteredString;
  cout << "Your String was:" << endl;
  cout << enteredString << endl;

  return(0);
}

【问题讨论】:

  • 上面的 sn-p 确实有这个:#include &lt;string&gt;。你的原始代码有吗?
  • 在文件顶部说 #include &lt;string&gt;

标签: c++ endl


【解决方案1】:

您的#define 末尾有一个分号。这成为宏的一部分,所以预处理后的代码如下所示:

cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;

去掉分号就可以了。


PS:为此使用实常数通常比依赖预处理器更好:

const char *STRING = "C++ is working on this machine usig the GCC/G++ compiler";

【讨论】:

  • 他还需要包含 用于“字符串输入字符串;”编译
  • @Peter:实际上&lt;iostream&gt; 的许多实现都会包含它。
  • @KillianDS:不过,你不应该依赖它来开发可移植代码。
【解决方案2】:

您的预处理器定义中有一个;。请注意,#DEFINE STRING x 只是将整个 x 语句(包括 ;)复制到它被引用的位置。

此外,预处理器常量不是语言常量。你应该使用const string STRING("C++ is working on this machine usig the GCC/G++ compiler");

【讨论】:

  • 嗯,有道理,菜鸟错误。哦,你会知道为什么只打印我的字符串的第一个单词吗?谢谢。
  • @VisionIncision: cin &gt;&gt; enteredString 只读一个字。要阅读整行,请使用getline(cin, enteredString)
【解决方案3】:

#define 末尾有一个分号 - 这将被替换到您的代码中,给出。

cout &lt;&lt; "C++ is working on this machine usig the GCC/G++ compiler"; &lt;&lt; endl;

【讨论】:

    【解决方案4】:

    因为您在 STRING 之后有一个分号。删除它并尝试一下...

    【讨论】:

      【解决方案5】:

      删除STRINGS 定义中的;

      【讨论】:

        【解决方案6】:

        中删除;
        #define STRING "C++ is working on this machine usig the GCC/G++ compiler"
        

        【讨论】:

          【解决方案7】:

          删除#define STRING末尾的;,然后重试。

          【讨论】:

            【解决方案8】:

            define 是一个预处理器指令。这将替换定义宏之后的所有内容,在本例中为 STRING。因此,请删除最后一个分号 (;),该分号 (;) 会在违规行中展开时放置语句结束标记。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-06-05
              • 2012-06-29
              • 1970-01-01
              • 2015-07-19
              • 2011-07-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多