【问题标题】:C++ program sees an included .txt file as codeC++ 程序将包含的 .txt 文件视为代码
【发布时间】:2012-07-10 08:02:57
【问题描述】:

我只是在学习输入/输出流的最基本方面,似乎无法让我的程序读取文本文件。它给我的错误表明它正在尝试将 .txt 文件作为 C++ 代码读取,而我只是使用其中的值来测试我的流。

这些是我包含的 .txt 文件的内容:

12345
Success

这是主程序的代码:

#include <fstream>
#include <iostream>
#include "C:\Users\Pavel\Desktop\strings.txt"
using namespace std;

int main (int nNumberOfArgs, char* pszArgs[])
{
    ifstream in;
    in.open("C:\Users\Pavel\Desktop\strings.txt");
    int x;
    string sz;
    in << x << sz;
    in.close();
    return 0;
}

我收到的第一条错误消息是“数字常量之前的预期不合格 ID”,它告诉我程序正在尝试编译包含的文件。如何防止这种情况并按预期读取文本文件?

【问题讨论】:

  • 您正在包含该文件,所以是的,编译器正在尝试将文件解析为代码。
  • 删除#include 后,您还应该将in &lt;&lt; x &lt;&lt; sz; 更改为in &gt;&gt; x &gt;&gt; sz;
  • 另外,修正路径in.open("C:\\Users\\Pavel\\Desktop\\strings.txt")

标签: c++ include text-files c-preprocessor iostream


【解决方案1】:

不要#include 你的 .txt 文件。包含用于源代码。他们以文本方式将文件插入到您的代码中,就好像您实际上已将其复制粘贴到那里一样。您不应该 #includeing 使用 ifstream 打开的文件。

【讨论】:

    【解决方案2】:

    在运行时打开文件系统上的文件不需要在源代码中提及该文件的名称。 (例如,您可以向用户询问文件名,然后打开它就好了!)

    如果您希望将数据嵌入到程序的可执行文件中(因此在运行时不依赖文件系统上的文件),您可能会在源代码中使用#include 数据。但要做到这一点,您必须将文件格式化为有效的 C++ 数据声明。所以那时它不会是.txt 文件。

    例如,在strings.cpp中

    #include <string>
    
    // See http://stackoverflow.com/questions/1135841/c-multiline-string-literal
    std::string myData =
        "12345\n"
        "Success";
    

    然后在你的主程序中:

    #include <iostream>
    #include <sstream>
    #include "strings.cpp"
    using namespace std;
    
    int main (int nNumberOfArgs, char* pszArgs[])
    {
        istringstream in (myData);
        int x;
    
        // Note: "sz" is shorthand for "string terminated by zero"
        // C++ std::strings are *not* null terminated, and can actually
        // legally have embedded nulls.  Unfortunately, C++ does
        // have to deal with both kinds of strings (such as with the
        // zero-terminated array of char*s passed as pszArgs...)
        string str;
    
        // Note: >> is the "extractor"
        in >> x >> str;
    
        // Note: << is the "inserter"
        cout << x << "\n" << str << "\n";
    
        return 0;
    }
    

    一般来说,只是#include-ing 像这样的源文件不是你想做的事情的方式。如果您在项目中的多个文件中执行此操作(myData 的重复声明),您很快就会遇到麻烦。所以通常的技巧是把东西分成头文件和实现文件……包括头文件,你想多少次都行,但只把一个实现的副本放到你的构建过程中。

    【讨论】:

      【解决方案3】:

      #include 指令的工作方式与所包含文件的扩展名相同 - txt、h,根本没有扩展名 - 没关系。它的工作原理是在将该文件传递给编译器之前,预处理器将文件的内容粘贴到您的源文件中。就编译器而言,还不如自己复制粘贴内容。

      【讨论】:

      • “就编译器而言,你还不如自己复制粘贴内容。” -- 技术上是正确的,但魔鬼在细节中.例如,__FILE__ 将报告 #included 文件的名称,但如果您粘贴内容,它将评估为以前的名称 -#includeing 源。 :-/ (“就编译器而言”与“就预处理器而言”之间的细微差别,值得一提。)
      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 2019-02-19
      相关资源
      最近更新 更多