Question

I want to read the content of a file with c++. Im using ifstream, but here is an error at compiling:

Code:

#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();

And the Error:

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()) {
 ^

I hope you can help me, thanks!

Was it helpful?

Solution

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

OTHER TIPS

There are a few issues. The main one (causing the error) is that in C++ you can't just have code living on its own. It all goes into functions. In particular, you have to have the main function.

Also, your read loop is not going to work correctly. You should read into a std::string, that will keep track of the memory for you, and the current way you would miss the last string. I would suggest reading a line at a time. Something like this:

#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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top