【问题标题】:C++ ifstream type errorC++ ifstream 类型错误
【发布时间】:2013-12-21 10:41:40
【问题描述】:

我想用 c++ 读取文件的内容。我正在使用 ifstream,但编译时出现错误:

代码:

#include <Python.h>
#include <iostream>
#include <fstream>

using namespace std;

ifstream script;
script.open("main.py");
const char *programm;
if (script.is_open()) {
    while (!script.eof()) {
        script >> programm;
    }
}
script.close();

还有错误:

main.cpp:8:1: error: 'script' does not name a type
 script.open("main.py");
 ^
main.cpp:10:1: error: expected unqualified-id before 'if'
 if (script.is_open()) {
 ^

希望你能帮助我,谢谢!

【问题讨论】:

  • 你需要把你的操作放到一个函数中!
  • 你能展示我必须做什么的代码吗?我不是专业人士,所以我不知道你的意思是什么
  • 你的主要功能在哪里?
  • 使用std::string。您正在尝试读取尚未分配内存的常量字符串。

标签: c++ gcc filestream ifstream


【解决方案1】:
#include <Python.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main(){

    ifstream script;
    script.open("main.py");
    // const char *programm; // You don't need a C string unless you have a reason.
    string programm;
    if (script.is_open()) {
        while (!script.eof()) {
            string line;
            script >> line;
            line += '\n';
            programm += line;
        }
    }
    script.close();
    // Now do your task with programm;
return 0;
}

【讨论】:

  • 如何将字符串转换为字符?
  • 哦!没有注意到:) 你不能写入输入流。运算符流运算符也不适用于数组。
【解决方案2】:

有几个问题。主要问题(导致错误)是在C++ 中,您不能只让代码独立存在。这一切都进入了功能。特别是,您必须拥有main 函数。

另外,您的读取循环将无法正常工作。你应该读到std::string,它会为你记录内存,以及你错过最后一个字符串的当前方式。我建议一次读一行。像这样的:

#include <Python.h>
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream script ("main.py");
    std::string line;
    if (!script) // Check the state of the file
    {
        std::cerr << "Couldn't open file\n";
        return 1;
    }
    while (std::getline(script, line)) // Read a line at a time.
        // This also checks the state of script after the read.
    {
        // Do something with line
    }
    return 0; // File gets closed automatically at the end
}

【讨论】:

  • 您希望将整个文件放在一个字符串中?这有点奇怪。您可以只使用另一个名为file 的字符串,然后在循环内执行file.push_back(line);。但这并不是一个好主意。大概有一些接口可以在您的程序中执行 python 脚本。你不能只通过文件名来做到这一点吗?
  • 请邀请我聊天
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2014-03-10
  • 2013-04-24
相关资源
最近更新 更多