A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
The file is empty because the code never writes anything to the ofstream and the loop bounds are off.
Key issues:
- No output to the file stream
The loop writes only tocout:
but never tocout << PLOTX[I] << ' ' << PLOTY[I] << ' ' << PLOTZ[I];out. To write to the file, useout:out << PLOTX[I] << ' ' << PLOTY[I] << ' ' << PLOTZ[I] << '\n'; - Incorrect include and file name
- The include should be:
not#include <fstream>#include fstream;. - The file path should include an extension and use consistent slashes, for example:
ofstream out("C:/Plot Data.txt");
- The include should be:
- Loop goes out of bounds
float PLOTX[20];defines indices0to19.
int INOW = 20;and
will accessI = 0; do { ... ++I; } while (I <= INOW);PLOTX[20]on the last iteration, which is out of range and undefined behavior. Use<and match the array size:int INOW = 20; // number of valid points int I = 0; while (I < INOW) { out << PLOTX[I] << ' ' << PLOTY[I] << ' ' << PLOTZ[I] << '\n'; ++I; } - Optional: check for file open errors
Before writing, verify the stream is good:ofstream out("C:/Plot Data.txt"); if (out.fail()) { // handle error: path invalid, no permission, etc. return 1; }
Putting it together:
#include <fstream>
#include <iostream>
using namespace std;
float PLOTX[20];
float PLOTY[20];
float PLOTZ[20];
int main() {
int INOW = 20; // number of points
ofstream out("C:/Plot Data.txt");
if (out.fail()) {
cout << "Failed to open output file" << endl;
return 1;
}
for (int I = 0; I < INOW; ++I) {
out << PLOTX[I] << ' ' << PLOTY[I] << ' ' << PLOTZ[I] << '\n';
}
out.close();
}
This will produce a text file with readable values.
References: