I am required to store the below console data into a text file:
enter image description here
However, the name of the textfile of where the output will be placed in is typed in by the user. I am unable to find a proper way to store all the console data in the requested text file. Since I use width and special spaces I am unsure how to go about doing this.
My Code:
if(message == "5"){
cout << "\n[View Data...]" << endl;
cout << "filtering criteria:" << optionTwo << endl;
cout << "sorting criteria:" << optionThree << endl;
cout << "sorting order:" << optionFour << endl;
cout << "" << endl;
if(optionTwo == "Point2D"){
std::cout.width(5); std::cout << std::right << "X";
std::cout.width(6); std::cout << std::right << "Y";
std::cout.width(9); std::cout << std::right << "Dist.";
std::cout.width(3); std::cout << std::right << "Fr" ;
std::cout.width(7); std::cout << std::right << "Origin" << endl;
}
}
if(message == "6"){
cout << "Please enter filename: " ;
cin >> message6;
}
When you are sending text into cout you are basically writing to a file already, just a system standard one called stdout. You simply need to open a different output file stream and send the output the same way.
#include <iostream>
#include <fstream>
using namespace std;
ofstream out = ofstream("file.txt", ios::out);
out.width(5);
out << std:;right << "X";
You do not strictly need to include the ios::out since it is the default mode for ofstream objects. You can read more at the cppreference
You can use filestreams for this:
std::cin >> message6; // read file name from the user
std::ofstream file {message6}; // open file with that name
file << "hello world"; // write data to the file
Similar to writing data to cout, you can use stream modifiers for file as well.
I don't know what kind of string you're using but, you can use the std::ostream for that:
ofstream myfile;
cout << "Please enter filename: " ;
cin >> message6;
myfile.open (message6);
Then instead of using cout, you'd use:
myfile << "Your string.\n";
But if you want to redirect he actual standard output of the program to a file. You can do it through calling arguments. And that can be set in the execution panel in your IDE or the terminal when the program is called
your_program >> output_file.txt
Related
I am just trying to read simple text file with ifstream. Suppose my text file looks like this (I don't know how to properly format it here, so here is how I wrote it notepad):
a\tb\nc\t\d\n
Output from reading text file using .seekg() before each .get() differs from output when .seekg() is called only before for loop (see output).
Question:
Is this expected behaviour? If yes then why is it happening?
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile("test.txt");
if (myfile)
{
cout << "Using seekg before each myfile.get():" << endl;
cout << "***********************" << endl;
myfile.seekg(0);
cout << (char)myfile.get();
myfile.seekg(1);
cout << (char)myfile.get();
myfile.seekg(2);
cout << (char)myfile.get();
myfile.seekg(3);
cout << (char)myfile.get();
myfile.seekg(4);
cout << (char)myfile.get() << endl;
cout << "***********************" << endl;
cout << "Using seekg only before loop:" << endl;
cout << "***********************" << endl;
myfile.seekg(0);
for (int i = 0; i <= 4; i++)
{
cout << (char)myfile.get();
}
cout << endl;
cout << "***********************" << endl;
myfile.close();
}
}
Output:
Output after running above code
After debugging:
In text file:
a is at position 0
'\t' is at position 1
b is at position 2
when .seekg(3) is used right before .get() then .get() returns '\n'
when .seekg(4) is used right before .get() then .get() returns '\n' also
when .seekg(0) is used only before for loop (see code) then .get() only returns single '\n' at position 3/4 , meaning '\n' is at the position 3 and 'c' is at position 4
I need to create a program that has 4 columns of words from an input file.
then randomly selects a word from each column and generates a sentence. The ultimate goal is to have a conversation that gets saved to the output file.
I've already created the code that reads the input file, and opens the output file to write on but i'm not sure how to select a word from a column and create the sentence, i'm guessing using an array would work but i'm not certain how to connect it with the file?
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string ifilename, ofilename, line;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
cout << "Hi, what's up? " << endl; // Pre-set opener
while (getline(inFile, line))
{
cout << line << endl;
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
You can use a 2D vector of strings to store the words of the sentences and use a random number generator like rand to pick a particular row element from every column. Something like the following
vector<vector<string>> myConversationVector;
while (choice != "no")
{
std::cout << myConversationVector[rand() % 5][0] <<" "
<< myConversationVector[rand() % 5][1] <<" "
<< myConversationVector[rand() % 5][2] <<" "
<< myConversationVector[rand() % 5][3];
}
I am trying to use fstream but am running into problems when trying to open a file from within Visual Studio 2013. In Visual Studio, I have two resources that I have enabled to be used in the project titeld input1.txt and input2.txt . If I directly run the application from the Debug folder using File Explorer, I am able to use the ifles. If I try to run it from within Visual Studio with ctrl, neither files can be found. I believe my code is correct, but I'm not sure what changes to make to the project to have it run correctly.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const bool VERBOSE(true);
int main(){
ifstream input;
ofstream output;
string inFileName;
string outFileName;
string tempString;
// Get input file name into a string
cout << "Input file name: " << flush;
cin >> inFileName;
if (VERBOSE)
{
cout << "Input file name is " << inFileName << endl;
}
// Convert filenames to C strings and use stream.open()
input.open(inFileName.c_str());
if (input.fail())
{
cout << "File " << inFileName << " cannot be opened" << endl;
return -1;
}
// Get output file name into a string
cout << "Output file name: " << flush;
cin >> outFileName;
if (VERBOSE)
{
cout << "Output file name is " << outFileName << endl;
}
// Convert filenames to C strings and use stream.open()
// When opening output file, it will create the file if it
// does not exist, and will clobber it if it does.
output.open(outFileName.c_str());
if (output.fail())
{
cout << "File " << outFileName << " cannot be opened" << endl;
return -2;
}
// While there is more to the input file, get a word
// and copy it to the output file on its own line.
while (!input.eof())
{
input >> tempString;
if (VERBOSE)
{
cout << " Length is " << tempString.length() << " for " << flush;
}
if (tempString.length() > 0)
{
if (VERBOSE)
{
cout << tempString << endl;
}
output << tempString << endl;
}
else
{
if (VERBOSE)
{
cout << "No more input" << endl;
}
}
// This is needed to keep the last non-whitespace word
// read in from being printed twice if the file ends in
// whitespace, including a newline.
tempString.clear();
}
cout << endl;
return 0;
}
Specify the full path to the files when you cin them.
I have developed a frame work for a scripting language and I am trying to make a compiler for it to output onto a certain file a custom Hex code to be read by an interpreter for applications such as games and movies. The interpreter will read the hex and perform operations via loops and pretty much do the hard work for me. But I need a way to compile the strings of text into my custom hexadecimal. Here is an example of my compiler.
#include <iostream>
#include <string>
#include <Windows.h>
#include <wincon.h>
#include <fstream>;
using namespace std;
int main(){
char egScriptpath[999];
char path[999];
char title[999];
ifstream readfile;
ofstream myfile;
int optn;
cout << "Enter the path where your *.egSCRIPT file is: " << endl;
cin.getline(egScriptpath,999);
cout << "Enter your path where you want to compile your *.egSCRIPT file: " << endl;
cin.getline(path,999);
cout << "Enter your title for your program: ";
cin.getline(title,999);
cout << endl << "Enter for your option of file extention:" << endl;
cout << " Enter 1 for .egGame :" << endl;
cout << " Enter 2 for .egMovie: ";
cin >> optn;
if(optn==1){
readfile.open((string)egScriptpath);
ofstream egMovieFile((string)path+"\\"+(string)title+".egGame");
myfile.open((string)path+"\\"+(string)title+".egGame");
while(!readfile.eof()){
if(readfile.getline("validated()",1)){
myfile << " \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" ////////////////\n"
" ////////////////\n"
" ||||||||||||||||\n"
" ||||||||||||||||\n"
" ||||||||||||||||\n"
" \1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\n"
" \2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\n";
}
}
myfile.close();
readfile.close();
}else if(optn==2){
readfile.open((string)egScriptpath);
ofstream egGameFile((string)path+"\\"+(string)title+".egMovie");
myfile.open((string)path+"\\"+(string)title+".egMovie");
while(!readfile.eof()){
if(readfile.getline("validated()",1)){
myfile << " \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n"
" ////////////////\n"
" ////////////////\n"
" ||||||||||||||||\n"
" ||||||||||||||||\n"
" ||||||||||||||||\n"
" \1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\n"
" \2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\n";
}
}
myfile.close();
readfile.close();
}
cout << "Compile complete" << endl;
system("pause");
return 0;
}
So what I want to do is in the if statement where it says if(readfile.getline("validated()",1)){} I want it to write onto the "myfile" ofstream variable the text that you can see just for an example. I hope I am clear on what I am saying. If the compiler reads "validated()" on my script file, then it will write the "hexadecimal" code onto the new file with the variable of "myfile" which will in return be interpreted by the interpreter for applications such as games and movies. Thanks if you know what is wrong and why it is not writing the hex code onto the new file that it makes.
Looks like your problem is located here:
if(readfile.getline("validated()",1)){
Sincerely, I don't even know why the compiller allows you to do so, but I would like to suggest to you the following change:
instead of:
while(!readfile.eof()){
if(readfile.getline("validated()",1)){
use this one:
std::string buffer;
while (std::getline(readfile, buffer, '\n')){
if (buffer == "validated()")
also, since you are using C++, instead of use arrays of char, you should relly more on std::string class.
Down below is my incomplete program. I am having problems with writing to a text file. For example I want to write the number of snow days to a text file, but nothing shows up in the textfile when I debug in VS 2010. It does display my info and name, but nothing else works. It wont write anything after that. its NOT writing to a text file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
const string INFORMATION = "College Class";
const string MY_NAME = "Tom Hangler";
int main(void)
{
ofstream outFile;
int numberOfSnowDays;
int greatestSnowDay;
int dayNumber;
double amounttOfSnow;
outFile.open("Ex1Out.txt");
outFile << setw(51) << INFORMATION << endl << setw(48) << MY_NAME << endl;
cout << "Please enter num of days it snowed: " << endl;
cin >> numberOfSnowDays;
outFile << setw(10) << "Number of days of snow is: " << setw(10) << numberOfSnowDays;
int index;
//Problem 1 for-loop
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
};
return 0;
}
here is what my output displays:
College Class (centered)
Tom Hangler (centered)
If i try to write anything after this, Nothing is written ever to the output file. And the output text file IS in my VS project that contains my .cpp file. I added the text file to project.
Try closing the stream at the end of the function, it looks like the data isn't getting flushed.
outFile.close();
Your code compiles and works on gcc 4.4.5 (apart from typo in amounttOfSnow).
Is it possible that you are looking at an old Ex1Out.txt file ?
Its most likely created in the Release or Debug subdirectory in your project, not where the .cpp files are.
in your for loop, you only collect the amount of snow, but you don't write it to the text file.
Do you want to do something like this?
...
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
// next line is new:
outFile << "Day#: "<< dayNumber << ", snow: "<< amountOfSnow<<endl;
};
outFile.close()
...