C++ ifstream类型错误

3
我希望能够用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()) {
 ^

希望你能帮助我,谢谢!


2
你需要将你的操作放到一个函数中! - billz
你可以展示一下代码让我知道具体需要做什么吗?我不是专业人士,不太清楚你的意思。 - Tekkzz
你的主函数在哪里? - sorush-r
使用std::string。您正在尝试读取未分配内存的常量字符串。 - chris
2个回答

3
#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;
}

如何将字符串转换为字符? - Tekkzz
哦!没注意到 :) 你不能向输入流写入。此外,流运算符也无法在数组上工作。 - sorush-r

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脚本,你能否通过传递文件名来实现这个功能呢? - BoBTFish
请邀请我加入聊天。 - Tekkzz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接