#include <cstdlib>
#include <stdio.h>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
usingnamespace std;
int main(int argc, char** argv)
{
//first input text stream from file
//tokenize
//parse each token against structure functions for each command type
//structure functions will depend on some symbol in lookup table
//store data in parse tree nodes
//connect nodes into an n-tree
cout << "Open what file?";
char* str;
cin >> str;
fstream myfile(str,ios::in);
string x;
if(myfile.is_open())
{
while(getline(myfile,x))
{
cout << "1";
}
}
cout << x;
myfile.close();
return 0;
}
I'm trying to load a file input stream to load all the character content into a variable (say from a .java file for example), but for some reason whenever I type in the name of the file I want to stream I get the report: RUN FAILED (exit value 1, total time 2s)
#include <cstdlib>
#include <stdio.h>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
usingnamespace std;
int main(int argc, char** argv)
{
//first input text stream from file
//tokenize
//parse each token against structure functions for each command type
//structure functions will depend on some symbol in lookup table
//store data in parse tree nodes
//connect nodes into an n-tree
cout << "Open what file?";
std::string str;
cin >> str;
fstream myfile(str.c_str(),ios::in);
string x;
if(myfile.is_open())
{
while(getline(myfile,x))
{
cout << "1";
}
}
cout << x;
myfile.close();
return 0;
}
Notice how we use str.c_str()to convert the std::string to a C-String or char array...
You can do that, but I suggest you to turn on C++11 support in your compiler, or upgrade if it is outdated. Aside from saner interface for many funnctions you will get a load of awesome features.
#include <fstream>
#include <iostream>
#include <string>
int main(){
usingnamespace std;
ofstream src("my_file.txt");
if(!src.is_open())
return -1;
string file, line_holder;
while(getline(src, line_holder)){
file += line_holder + "\n"; //Collect each line, re-adding the thrown away character
line_holder.clear();
}
//file.pop_back(); //Optional to get rid of the extra newline character we inserted
src.close();
cout << "I read:\n\n" << file;
return 0;
}