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;
}
Related
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
Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int x;
string line;
vector<int> vect;
ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt");
inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt");
if (inFile.is_open()) {
while (getline(inFile, line))
{
cout << line << '\n';
}
inFile.close();
}
else {
cout << "Unable to open file";
exit(1); // terminate with error
}
return 0;
}
The path to the file that i wrote is correct such that the file opens, but when the program runs it doesn´t cout the lines that i wrote on the txt file to the cmd, i dont know if this is somewhat important but im coding in visual studio 2019.
I can't seem to find the answer to this problem anywhere in the internet and to be honest i think im doing it right, any help would be much appreciated,thanks in advance.
You are trying to open the inFile twice. First time during inFile construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt"), second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt"), when it's already open, which is erroneous, and flags the stream as no longer good.
3 possible fixes:
Remove inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt")
Use default constructor, without specifying the file name
inFile.close() before you open it again (obviously, not the nicest fix).
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 have a problem working in C++ with txt files.. First of all, I want to make a program which
have .cpp and .h files.. which have classes and functions.
So here is my problem:
for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.
Here is program code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
int i;
string player[5];
ifstream myfile ("1-Efes Pilsen.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
for (i=0;i<5;i++)
{
getline (myfile,line);
player[i] = line;
}
// after this point I still can use new variables
}
}
else cout << "Unable to open file";
cout << player[1]; // <--- NOT WORKING. WHY?
myfile.close();
}
While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).
Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:
for (i=0;i<5 && myfile.good();i++)
{
getline (myfile,line);
player[i] = line;
}