I have a txt file, named mytext.txt, from which I want to read and save every line in C++. When I run the binary, I do ./file <mytext.txt
I'd like to do something
std::string line;
while(std::getline(std::cin,line)){
//here I want to save each line I scan}
but I have no clue on how to do that.
You can use a std::vector<string> to save the lines as so:
///your includes here
#include <vector>
std::vector<std::string> lines;
std::string line;
while(std::getline(std::cin,line))
lines.push_back(line);
You can look at the following documentation and example:
http://www.cplusplus.com/doc/tutorial/files/
Edit upon recommendation:
In the provided link below they explain how to open and close a text file, read lines and write lines and several other functionalities. For completeness of this answer an example will be given below:
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The above script will write the 2 lines into the text file named example.txt.
You can then read these lines with a somewhat similar script:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Best regards
Ruud
Related
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
I need someone to edit that code so that i could display a file!!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string data; //enter a data as a string
ifstream datafile; // input datafile as ifstream
datafile.open("test.txt"); // open test file
}
Unfortunately you didn't specify how you want to read and display the file. Thus I made the assumption that output should go to std::cout. In the attached proposal there are two possibilities to read: line-by-line as you would read the file in any text editor or each word separately in a new line (input separated by White spaces, i.e. blanks, Tabulators or line breaks).
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string data; //enter a data as a string
std::ifstream datafile; // input datafile as ifstream
datafile.open("Source.cpp"); // open test file
// read line by line
while (std::getline(datafile, data))
{
std::cout << data << std::endl;
}
/*
// read each word (separated by white spaces)
while (!datafile.eof())
{
datafile >> data;
std::cout << data << std::endl;
}
*/
datafile.close();
return 0;
}
There is no error handling in. If the file does not exist or any other occurs no exceptions will be caught.
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)
Here is my requirement: "I need to show to the user on a Console window, the output of a .txt file which will be modified continuously by a Third party application"
I have this code from cplusplus.com:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("test_results.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Do I need any sort of time counter to read that file at certain regular intervals of time? Guide me, thanks in advance...
There are two approaches.
Platform-dependent
Use API, like inotify in Linux
Platform-independent
Query fs about file modifications, for example using boost::filesystem
http://www.boost.org/doc/libs/1_52_0/libs/filesystem/doc/reference.html#last_write_time
I'm trying to solve Problem 13 of project euler, which involves the sum of 100 50 digit numbers. I figured there would be a better way than the paste that whole chunk of numbers into my code. So I searched around and found that you could paste the chunk into a .txt file and read it from there.
So, how would I go about reading from a .txt file in C++ and more importantly getting the 50 digit strings individually from it?
Something like this?
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
int i = atoi(line.c_str());
// do here something with 'i'
cout << i
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}