Can any body help me with this simple thing in file handling?
The following is my code:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream savefile("anish.txt");
savefile<<"hi this is first program i writer" <<"\n this is an experiment";
savefile.close();
return 0 ;
}
It is running successfully now, I want to format the output of the text file according to my way.
I have:
hi this is first program i writer this is an experiment
How can I make my output file look like the following:
hi this is first program
I writer this is an experiment
What should I do to format the output in that way ?
#include <fstream>
using namespace std;
int main(){
fstream file;
file.open("source\\file.ext",ios::out|ios::binary);
file << "Line 1 goes here \n\n line 2 goes here";
// or
file << "Line 1";
file << endl << endl;
file << "Line 2";
file.close();
}
Again, hopefully this is what you want =)
First, you need to open the stream to write to a file:
ofstream file; // out file stream
file.open("anish.txt");
After that, you can write to the file using the << operator:
file << "hi this is first program i writer";
Also, use std::endl instead of \n:
file << "hi this is first program i writer" << endl << "this is an experiment";
// Editor: MS visual studio 2019
// file name in the same directory where c++ project is created
// is polt ( a text file , .txt)
//polynomial1 and polynomial2 were already written
//I just wrote the result manually to show how to write data in file
// in new line after the old/already data
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("poly.txt", ios::out | ios::app);
if (!file) {
cout << "File does not exist\n";
}
else
{
cout << "Writing\n";
file << "\nResult: 4x4 + 6x3 + 56x2 + 33x1 + 3x0";
}
system("pause");
return 0;
}
**OUTPUT:** after running the data in the file would be
polynomial1: 2x3 + 56x2-1x1+3x0
polynomial2: 4x4+4x3+34x1+x0
Result: 4x4 + 6x3 + 56x2 + 33x1 + 3x0
The code is contributed by Zia Khan
use ios_base::app instead (adding lines instead of overwriting):
#include<fstream>
using namespace std;
int main()
{
ofstream savefile("anish.txt", ios_base::app);
savefile<<"hi this is first program i writer" <<"\n this is an experiment";
savefile.close();
return 0 ;
}
Related
I've been trying to write a program to open a file in both read and write mode:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream obj;
obj.open("hello.txt",ios::in|ios::out);
if (!obj){
cout << "File not opened" <<endl;
return 1;
}
obj << "Hi How are you" ;
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
obj.close();
return 0;
}
When I compile this program on Visual Studio Code on Windows, though the text "Hi how are you" is printed in the file, the contents of the file are not printed on my screen. Can someone tell me what might be the problem?
Resetting the position indicator with seekp to 0 helps, because both output and input indicators are set to the end of file after write operation (you can read them with tellp tellg).
obj << "Hi How are you" ;
obj.seekp(0);
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
Considering avoiding using obj.eof(), you can e.g. read your file line by line:
std::string line;
std::getline(obj, line);
std::cout << line << std::endl;
or in the loop:
while (std::getline(obj, line)) // here std::basic_ios<CharT,Traits>::operator bool is used to check if operation succeeded
{
std::cout << line << std::endl;
}
You got two problems there: buffering and seek position.
Buffering:
When you write the text with obj << "Hi How are you, you just write it into the buffer and the text gets written into the file after flushing the buffer. You can adjust which buffer type you want to use. The easiest way is to write std::endl after your text if you use line buffering.
A better explaination is already here
Seek Position:
You are reading from the last position in your file. You have to manually change the read position to the first character in the file, then you are done.
I am writing a small program to just get the lines from a srt file in a specific format. However I am getting a garbage value in the very first (and only that) read I do using getline. Can someone point out why am I getting this abnormal behaviour?
//Small program to get the text from the srt files.
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<vector>
#include<sstream>
#include<conio.h>
using namespace std;
void srtToTranscript(ifstream* iFile, ofstream *oFile);
int main(){
std::string file_name;
std::string transcript;
cout << "Enter srt file name (without extension)";
cin >> file_name;
ifstream iFile;
ofstream oFile;
iFile.clear();
iFile.open("data\\" + file_name+".srt");
oFile.open("data\\" + file_name + "_result.txt");
srtToTranscript(&iFile,&oFile);
cout << "Conversion done. Check in the same folder";
cout << "Press a key to exit... ";
while (!_kbhit());
char dummy = _getch();
return 0;
}
void srtToTranscript(ifstream* iFile, ofstream* oFile)
{
int i = 1;
std:string line;
for (; getline(*iFile, line);)
{
cout << line << endl;
cout << to_string(i) << endl;
if (line.compare(to_string(i)) == 0){
getline(*iFile, line);
i++;
continue;
}
*oFile << line + ",\n";
}
oFile->close();
}
appended is a sample of the file I am reading from:
1
00:00:00,000 --> 00:00:12,000
Translator: Thu-Huong Ha
2
00:00:12,038 --> 00:00:15,012
Over the last two decades, India has become
The problem is your ifile is not being opened successfully.
I'm seeing #include <conio.h> in your include list so I assume that you are working on Visual Studio? If you have use the default directory structure when setting up Visual Studio, then say that you have a project named: "Foo" Your .srt file needs to go here:
.../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo.srt
When I correctly placed the file there and at the prompt I entered:
Foo
I got this output in: ".../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo_result.txt":
00:00:00,000 --> 00:00:12,000,
,
Translator: Thu-Huong Ha,
,
00:00:12,038 --> 00:00:15,012,
,
Over the last two decades, India has become,
One thing I'd make sure of is that your line declaration in srtToTranscript is defined:
string line
Not:
std:string line
I wrote some code in order to double space a file in C++, currently the program takes in one file and returns a different file, that is double spaced. I want the program to return the same file to the file directory. I'm pretty at this point I need to a use a temporary file, which is fine, but I would like to at the end of the program eventually return the same file(but double spaced to the user). Any help would be appreciated. Here is my code thus far.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main( )
{
ifstream fin;
ofstream fout;
fin.open("story.txt");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("numstory.txt");
if (fout.fail( ))
{
cout << "Output file opening failed.\n";
exit(1);
}
char next;
int n = 1;
fin.get(next);
fout << n << " ";
while (! fin.eof( ))
{
fout << next;
if (next == '\n')
{
fout << endl;
}
fin.get(next);
}
fin.close( );
fout.close( );
return 0;
}
As you suggest, create a temporary file and then, only when processing has been successful, remove the existing file and rename the temporary file.
By the way, putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.
Simplest solution: delete the input file and rename the new one (remove and rename)
Better solution: open the first file for both reading and writing (fstream) and replace the content with a stringstream buffer without even creating a temporary file (also faster).
You have plenty of choices.
I currently have this code, but I would like to be able to output to a .csv file, rather than just print to screen. Does anyone know how to do this?
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
cout << Weather_test;
return 0;
}
If the Weather_test string is formatted properly.
ofstream Weather_test_output("path_goes_here.csv", ios::app);
// this does the open for you, appending data to an existing file
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
If it is not formatted properly then you need to separate it into "fields" and write them with commas between them. That's a separate question.
Writing a string to a CSV file is like writing a string to any file:
std::string text = "description"
output_file << description << ", " << 5 << "\n";
In your example, you can't write to an ifstream. You can write to ofstream and fstream but not ifstream.
So either open the file for reading and writing or close after reading and open as writing.
To write to csv is to create an ostream and open file named "*.csv". You can use operator<< on this object in the same way as you have used it previously to write to the standard output, std::cout:
std::ofstream f;
f.open( "file.csv", std::ios::out);
if ( !f) return -1;
f << Weather_test;
f.close();
Thanks people you here are all truly amazing!
I managed to get my final piece of code which (removes all letters of the alphabet from my .csv file). Here it is for posterity
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
string Weather_test;
int main()
{
ifstream Weather_test_input;
Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv");
getline(Weather_test_input, Weather_test, '?');
Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end());
ofstream Weather_test_output("/Users/MyName/Desktop/Weather_test_output.csv", ios::app);
Weather_test_output << Weather_test << std::endl;
Weather_test_output.close();
cout << Weather_test;
return 0;
}
Thanks again all!
First task of the tutorial and I'm already stumped,
Right, I'm supposed to write down 3 numbers into a text file, open that file up, output all 3 numbers and the average. Managed to get the first 2 parts done but I've hit a wall at the actual output part.
Here is the contents of the text file exactly as it appears within the file:
25
10
12
And here is the code I have so far:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create an ifstream input stream for reading of data from the file
ifstream inFile;
inFile.open("ProgrammingIsFun.txt");
// Create an ofstream output stream for writing data to a file
ofstream outFile;
outFile.open("Results.out");
cout << "The first integer is " << endl;
cout << "The second integer is " << endl;
cout << "The third integer is " << endl;
cout << "The average is " << endl;
// Close the files since we're done with them
outFile.close();
inFile.close();
system("Pause");
return 0;
}
From what I understand the contents of the txt file can only contain those 3 numbers and nothing else (I could be wrong though)
Any help would be much appreciated.
I'm guessing that the preferred C++ way of reading integers from files would be:
int first, second, third;
inFile >> first;
inFile >> second;
inFile >> third;
You can then analogously output using the << operator on outFile.