The following is my C++ program:
main.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fileWriter;
fileWriter.open ("firstFile.cpp");
fileWriter << "#include <iostream>" << endl;
fileWriter << "int main() {" << endl;
fileWriter << "\tstd::cout << \"hello world\" << std::endl;" << endl;
fileWriter << "\treturn 0;" << endl;
fileWriter << "}" << endl;
fileWriter.close();
return 0;
}
When the above program is executed, it creates a text-file named "firstFile.cpp" containing the following code:
firstFile.cpp
#include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
which, when executed, prints "hello world" on the screen.
So, I would like to add to the main.cpp file lines of code asking GCC to compile the new firstFile.cpp just created.
I am using GNU gcc on both platform Ubuntu and Windows.
Is it possible to get any error code form the call to the compiler? If not why.
This is not too difficult using the std::system command. Also raw string literals allow us to insert multiline text which is useful for typing in program parts:
#include <cstdlib>
#include <fstream>
// Use raw string literal for easy coding
auto prog = R"~(
#include <iostream>
int main()
{
std::cout << "Hello World!" << '\n';
}
)~"; // raw string literal stops here
int main()
{
// save program to disk
std::ofstream("prog.cpp") << prog;
std::system("g++ -o prog prog.cpp"); // compile
std::system("./prog"); // run
}
Output:
Hello World!
gcc is an executable, so you have to use either system("gcc myfile.cpp") or popen("gcc myfile.cpp"), which gives you a filestream as result.
But since you are generating code anyways, you don't even need to write it to a file. You can open the gcc proces with FILE* f = popen("gcc -x ++ <whatever flags>"). Then you have you can write your code with fwrite(f, "<c++ code>"). I know this is c and not really c++ but it might be useful. ( I don't think there is a c++ version of popen()).
All you need to do is add the following line after you create your file.
system("g++ firstFile.cpp -o hello");
Works on OS X so I hope it will work for you too.
To use the command line of a compiler in source file use system function.
Syntax of which is :
int system (const char* command); //built in function of g++ compiler.
In your case, it should be like
system("g++ firstFile.cpp");
PS: system function does not throw Exceptions.
Program
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
ofstream fileWriter;
fileWriter.open ("firstFile.cpp");
fileWriter << "#include <iostream>" << endl;
fileWriter << "int main() {" << endl;
fileWriter << "\tstd::cout << \"hello world\" << std::endl;" << endl;
fileWriter << "\treturn 0;" << endl;
fileWriter << "}" << endl;
fileWriter.close();
system("g++ firstFile.cpp");
return 0;
}
Depending on what you actually want to achieve you could also consider embedding some C++ compiler into your application.
Note that this is by far not as easy as calling an external executable, and might be subject to licence restrictions (GPL).
Also note that by using std::system or a similar mechanism you add the requirement on your target environment to actually have the called compiler available (unless you somehow bundle it with your application).
Something like this:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fileWriter;
fileWriter.open ("firstFile.cpp");
fileWriter << "#include <iostream>" << endl;
fileWriter << "int main() {" << endl;
fileWriter << "\tstd::cout << \"hello world\" << std::endl;" << endl;
fileWriter << "\treturn 0;" << endl;
fileWriter << "}" << endl;
fileWriter.close();
system("c firstFile.cpp");
return 0;
}
or whatever command is appropriate for the compiler you're using.
Related
I recently started using Eclipse CDT (version 2019-03) with the Cygwin toolchain and have noticed some bizarre behaviour when using the debugger.
Under the debugger the following program behaves as you would expect
#include <iostream>
int main()
{
std::cout << "hello world\n" << std::flush;
}
However the following produces no output
#include <iostream>
int main()
{
std::cout << "* world\n" << std::flush;
}
And for the following the output is world
#include <iostream>
int main()
{
std::cout << "# world\n" << std::flush;
}
This behaviour is completely consistent and reproduceable. Does anyone have any explanation or workarounds?
I have been playing around with the fstream class in C++ to see if I am able to write some data to a text file(.txt). According to what I know, If the program tries to write to a file that does not exist then it would automatically create that file, am I wrong? This program is very simple and does not give me any compiler errors which means it builds fine. However for some reason it crashes when I run it.
Here is my code:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
std::fstream* myFile;
int main()
{
int age = 15;
std::string myName = "Javier Martinez";
std::string friendsName = "David Lyn";
//Backslash is a special character, use double backslash or forward slash instead.
myFile->open("C:/Users/NIKE/Desktop/data.txt");
if (myFile->fail())
{
std::cerr << "File was unable to be opened.";
}
*myFile << age << "\n";
*myFile << myName << "\n";
*myFile << friendsName << "\n";
myFile->close();
std::cout << "File was successfully written to with the data";
return 0;
}
Any help is appreciated. Thank you in advance.
NOTE: I am using the GNU GCC compiler with Code::Blocks IDE
myFile is uninitialized. Check it.( Allocate memory) or simply use fstream.
Your problem stems from the line:
std::fstream* myFile;
You only declared a pointer to a stream object, which is initialized to nullptr by reason of it being in the global scope. The fact that you tried accessing a non-existent object (invalid) through it, you invoked what is known as Undefined Behavior.
You do not need to allocate stream objects on the heap, rather, do:
std::fstream myFile;
On a side Note: Check your program control flow:
if (!myFile)
{
std::cerr << "File was unable to be opened.";
}
else{
myFile << age << "\n";
myFile << myName << "\n";
myFile << friendsName << "\n";
}
This question already has an answer here:
gnuplot-cpp cannot feed command to pipe
(1 answer)
Closed 8 years ago.
I'm trying to implement the code below from this site:
https://sites.google.com/site/bettereaclone/introduction/gnuplot/c-example-gnuplot-1
Code:
#include <iostream>
#include "gnuplot_i.hpp"
#include <windows.h>
#include <conio.h>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
try
{
Gnuplot g1("lines");
cout << "*** plotting slopes" << endl;
g1.set_title("Slopes\\nNew Line");
cout << "y = x" << endl;
g1.plot_slope(1.0,0.0,"y=x");
cout << "y = 2*x" << endl;
g1.plot_slope(2.0,0.0,"y=2x");
cout << "y = -x" << endl;
g1.plot_slope(-1.0,0.0,"y=-x");
g1.unset_title();
}
catch (GnuplotException ge)
{
cout << ge.what() << endl;
}
return 0;
}
I installed the gnuplot (http://www.gnuplot.info/download.html)
gnuplot_i.hpp file (https://code.google.com/p/gnuplot-cpp/source/browse/trunk/gnuplot_i.hpp)
When I run this code, I get this problem:
The error:
'C:/Program' is not recognized as an internal or external command,
operable program or batch file.
I've no idea why. thanks!!
Looks like path to gnuplot is malformed, not in quotation marks or simply not read properly.
Try forcing the path by uncommenting this line and correcting it to point gnuplot directory on your machine:
// Gnuplot::set_GNUPlotPath("C:/program files/gnuplot/bin/");
Suppose I've got code like
#include <iostream>
using namespace std;
int main() {
cout << "Redirect to file1" << endl;
cout << "Redirect to file2" << endl;
return 0;
}
I want to redirect the first output to file1 and the second to file2. Is that possible?
I think in C, fclose(stdout) and reopen the stdout might help but I'm not sure how to reopen it or whether it works.
Thanks
UPDATE: What for?
I have a program A, which reads input from the user and generates corresponding output. Now I want to check whether it is correct, I have a program B which generate input for A, as well as correct output. B will generate one set of test data at a time. And I will have thousands of tests.
On my machine, a thousand times ./B > ``mktemp a.XXX`` works better than using ofstream. Using fstream for thousands of times, my hard drive light flashes crazily. But not when redirecting to temp file.
UPDATE2:
In C++, it seems that the prevailing answer is cout along with cerr.
What about C, apart from stderr, can I close stdout and reopen it?
Why not use file streams ? this way it will most likely work regardless of the shell redirection:
#include <fstream>
#include <fstream>
using namespace std;
// opeen files
ofstream file1 ( "file1");
ofstream file2 ( "file2");
//write
file1 << "Redirect to file1" << endl;
file2 << "Redirect to file2" << endl;
//close files
file1.close();
file2.close();
You can use cout AND cerr.
cout << "Redirect to file1" << endl;
cerr << "Redirect to file2" << endl;
cerr goes to standard error
You can always use the standard error stream for e.g. error messages.
#include <iostream>
using namespace std;
int main() {
cout << "Redirect to file1" << endl;
cerr << "Redirect to file2" << endl;
}
For example, using the Windows [cmd.exe] command interpreter, and the Visual C++ cl compiler:
[D:\dev\test]
> type con >streams.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Redirect to file1" << endl;
cerr << "Redirect to file2" << endl;
}
^Z
[D:\dev\test]
> cl streams.cpp
streams.cpp
[D:\dev\test]
> streams 1>a.txt 2>b.txt
[D:\dev\test]
> type a.txt
Redirect to file1
[D:\dev\test]
> type b.txt
Redirect to file2
[D:\dev\test]
> _
EDIT: added colorized code and boldface emphasis.
Another way doing it is using cout.rdbuf() like this:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream cfile1("test1.txt");
ofstream cfile2("test2.txt");
cout.rdbuf(cfile1.rdbuf());
cout << "Redirect to file1" << endl;
cout.rdbuf(cfile2.rdbuf());
cout << "Redirect to file2" << endl;
return 0;
}
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Redirect to file1" << endl;
cerr << "Redirect to file2" << endl;
return 0;
}
Console:
test > 1.txt 2> 2.txt
1.txt:
Redirect to file1
2.txt:
Redirect to file2
I'm doing a C++ assingment for a class and I haven't used C++ in a decade so this might be something I'm missing that is simple; however ,I can't seem to figure it out.
I have a class I defined with a function that is producing no output; it looks like it's not even running and I don't have a clue why. Could someone point out my problem to me?
Issue: cout from the function getwords of the class readwords doesn't display any results.
Here is my class:
class readwords {
private:
char c;
//string aword;
public:
void getwords(std::istream& file) {
cout << "I got here" << std::flush;
/*while(file.good()) {
cout << "I got here\n";
c = file.get();
if(isspace(c)) cout << "\n"; //continue;
if(isalnum(c)) {
cout << c; //aword.insert(aword.end(),c);
}
}
*/
}
};
Which is being called from my main:
#include <fstream>
#include <stdlib.h>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
}
Thank you for any help you can provide.
Try to use a debugger. Most IDEs (NetBeans, Code::Blocks, etc) provide an interactive interface with gdb.
I just compiled and ran your code, but nothing wrong with the code itself,
except that I needed to include to use the 'cout' method.
"I got here" has been successfully displayed in my ubuntu machine.
What is your execution environment? You should check it first.
The problem appears to be redefining my own class. When actually coding the function I needed to use:
in readwords::countwords(std::istream& file) {
....
}
Once doing this output produced fine.