How do I write a string to a .csv file? - c++

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!

Related

In C++, opening a csv file with ifstream

I am trying to open a csv file in C++ using ifstream with a directory in the file path name. The file does reside in the specified directory location, but I observe an for the variable inFile when executing the code. My research up to this point says the code is correct, but something obviously is wrong. Any suggestions?
Thanks,
KG
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open("csvFile", ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
I found the answer to my csv file opening problem, a colleague assisted.
#David - You suggested removing the double quotes in the "inFile.open" line of code. In addition to removing the double quotes, I also needed to add c_str(), which "returns a pointer to a null-terminated character array with data equivalent to those stored in the string," .data() also performs the same function (cppreference.com).
#user4581301 - I am also aware that ios::in is implied with a ifstream, only included it here as a reference; thanks.
The modified code is listed below:
#include <string>
#include <fstream>
#include <iostream>
virtual void run()
{
string file_dir = "/home/datafiles/";
string csvFile = file_dir + "/myFile.csv";
ifstream inFile;
inFile.open(csvFile.c_str(), ios::in);
// file check to see if file is open
if(!inFile.is_open()) {
cout << "error while opening the file" << endl;
}
}
Really appreciate all the help.
Enjoy,
KG
Is this what you're trying to do?
#include <iostream> // std::{ cout, endl }
#include <string> // std::{ string, getline }
#include <fstream> // std::ifstream
auto main() -> int {
// Just to demonstrate.
// You want to use your real path instead of example.cpp
auto file = std::ifstream("example.cpp");
auto line = std::string();
while ( std::getline(file, line) )
std::cout << line << '\n';
std::endl(std::cout);
}
Live example

Read all character including the null byte

I want to read out the chrome history from its file. I want to get all characters and null byte that's in that file. The problem I'm facing is that I only get some part of the text that's in the file. I belive it stop due to a null byte or a speical character.
HereĀ“s my code that I have at the moment.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str;
std::ifstream in("c:/Users/Petrus/Documents/History"); // I have copy my file into my documents to make sure I'm not interfering with Chrome.
std::stringstream buffer;
if (!in.is_open()){
cout << "Failed to open" << endl;
}
else{
cout << "Opened OK" << endl;
}
buffer << in.rdbuf();
std::string contents(buffer.str());
while (getline(buffer, str))
{
cout << str;
}
in.close();
system("PAUSE");
return 0;
}
If you want to take a look at the chrome history file its located at:
C:\Users\YOUR NAME\AppData\Local\Google\Chrome\User Data\Default -->History
(PS You have to include hidden files to be able to see Appdata.)
Thanks in advance
std::getline() should be used only to read plain text files.
To read arbitrary binary files you should use read(). Additionally, on your operating system you must open binary files using the std::ios::binary flag.

fstream to display all text in txt

I want to display all the text that is in the fille to the output,
I use by using the code below, the code I got up and results posts are just a little out
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char str[10];
//Creates an instance of ofstream, and opens example.txt
ofstream a_file ( "example.txt" );
// Outputs to example.txt through a_file
a_file<<"This text will now be inside of example.txt";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstream b_file ( "example.txt" );
//Reads one string from the file
b_file>> str;
//Should output 'this'
cout<< str <<"\n";
cin.get(); // wait for a keypress
// b_file is closed implicitly here
}
The above code simply displays the words "This" does not come out all into output.yang I want is all text in the file appear in the console ..
The overloaded operator>> for char* will only read up to the first whitespace char (it's also extremely risky, if it tries to read a word longer then the buf length you'll end up with undefined behavior).
The following should do what you want in the most simple manner, as long as your compiler supports the rvalue stream overloads (if not you'll have to create a local ostream variable and then use the stream operator):
#include <fstream>
#include <iostream>
int main()
{
std::ofstream("example.txt") << "This text will now be inside of example.txt";
std::cout << std::ifstream("example.txt").rdbuf() << '\n';
}
try something like this
#include <fstream>
#include <iostream>
using namespace std;
int main(){
string line;
ofstream a_file ( "example.txt" );
ifstream myfile ("filename.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
a_file << line << '\n';
}
myfile.close();
a_file.close();
} else
cout << "Unable to open file";
}
Hope that helps
This is not the best way to read from a file. You probably need to use getline and read line by line. Note that you are using a buffer of fixed size, and you might cause an overflow. Do not do that.
This is an example that is similar to what you wish to achieve, not the best way to do things.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
ofstream a_file("example.txt");
a_file << "This text will now be inside of example.txt";
a_file.close();
ifstream b_file("example.txt");
getline(b_file, str);
b_file.close();
cout << str << endl;
return 0;
}
This is a duplicate question of:
reading a line from ifstream into a string variable
As you know from text input/output with C++, cin only reads up to a newline or a space. If you want to read a whole line, use std::getline(b_file, str)

Writing a string to the end of a file (C++)

I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++)
void main()
{
std::string str = "I am here";
fileOUT << str;
}
I realize there is much to be added to this and I do apologize if it seems I am asking people to code for me, but I am completely lost because I have never done this type of programming before.
I have attempted different methods that I have come across the internet, but this is the closest thing that works and is somewhat familiar.
Open your file using std::ios::app
#include <fstream>
std::ofstream out;
// std::ios::app is the open mode "append" meaning
// new data will be written to the end of the file.
out.open("myfile.txt", std::ios::app);
std::string str = "I am here.";
out << str;
To append contents to the end of files, simply open a file with ofstream (which stands for out file stream) in app mode (which stands for append).
#include <fstream>
using namespace std;
int main() {
ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode
fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file
fileOUT.close(); // close the file
return 0;
}
Open your stream as append, new text written to it will be written at the end of the file.
I hope that isn't your whole code because if it is, there's lots of things wrong with it.
The way you would write out to a file looks something like this:
#include <fstream>
#include <string>
// main is never void
int main()
{
std::string message = "Hello world!";
// std::ios::out gives us an output filestream
// and std::ios::app appends to the file.
std::fstream file("myfile.txt", std::ios::out | std::ios::app);
file << message << std::endl;
file.close();
return 0;
}

Creating files in C++

I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.
Can anyone help me?
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream reference
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.
Do this with a file stream. When a std::ofstream is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created.
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename = "/tmp/filename.txt";
int main() {
std::ofstream o(filename.c_str());
o << "Hello, World\n" << std::endl;
return 0;
}
This is what I had to do in order to use a variable for the filename instead of a regular string.
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
If you want to create a file with some content and don't need to deal with the ofstream after that you can simply write:
#include <fstream>
int main() {
std::ofstream("file.txt") << "file content";
}
no need to manually close the file, deal with variables, etc. The file is created, written, and closed in the same line.
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
use c methods FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending
r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();