This question already has an answer here:
Read data from fstream
(1 answer)
Closed 3 years ago.
How can I check if there is more content in a text file in c++ and if there is continue to read it?
I am trying to read a some words from a text file but the number of words is not specified.
Check out this link here.
Also, std:: is a reference to the namespace of code you are calling. When you include a file that is in the standard libraries, such as string, vector, fstream, iostream, you need to either declare that your file will use the namespace std with using namespace std; OR you append std:: to the method or variable.
Use std::vector and std::string. Use a correct form of reading a file:
std::string word;
std::vector<std::string> word_database;
while (text_file >> word)
{
word_database.push_back(word);
}
std::cout << "Words read: " << word_database.size() << "\n";
Related
This question already has answers here:
How do I read an entire file into a std::string in C++?
(23 answers)
Closed 4 years ago.
I'm looking for a way to way to read files in C++ I can write files, but here's where I'm stuck at:
ifstream readfile;
readfile.open("C:/Users/Crazy/Desktop/Useless.txt")
I 've seen people do things such as:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout << output;
}
}
myReadFile.close();
return 0;
}
But in
char output[100];
I want the whole thing read.
Also, I just want to only read it, not to check if it's already open, not to, check for errors. I just want to read the whole thing, and the whole thing only.
If you want to read the entire file into a variable you'll need to:
1. Determine size of file in characters.
2. Use std::vector and declare a vector of that size,
or use the new operator and dynamically allocate a char array.
3. Use ifstream::read to read in the entire file.
4. Close the ifstream.
5. Remember to delete the char buffer.
I recommend using an OS API to determine the file length.
Edit 1: Example
#include <iostream>
#include <fstream>
#include <vector>
std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);
I read about fstream, etc., a while ago. It says that ifstream is used to read data from a file, while ofstream is used to write data. I want to know that, what is the essence of using ifstream/ofstream if you can just use cin.getline() to fetch the data and cout << to print those?
ifstream: Stream class to read from files
ofstream: Stream class to write to files
Now what is a file?
Files are resources for storing information. For example, a text file.
Now, let's look at an example which explains ofstream.
Look at the following code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Here, we are writing something to a file. Writing information you can say.
Now, what is the difference between cin/cout and ifstream/ofstream?
cin is an object of class istream and cout is an object of class ostream. And in fact, we can use our file streams the same way we are already used to using cin and cout, with the only difference being that we have to associate these streams with physical files. Just think that cin/cout is a part of istream/ostream that is used for standard input/output.
Hope it helps a bit.
For more information, you can look at this link:
Input/output with files.
Ifstream()
ifstream() is used to input the file.
ifstream() is fstream() object it is used to input the single character or string or set of character to a file
it inherits the function get(), getline(), read(), etc...
Ofstream()
ofstream() is used to output the file
ofstream() is fstream() object it is used to output the single character or string or set of character from a file
it inherits the function put(), write(), etc...
This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 8 years ago.
I have a .txt file containing 6291456 numbers and nothing else. After reading all out and push_back into a vector, the vector.size() function returns 6291457. Where does this additional element come from?
int disparity;
ifstream disparity_txt;
disparity_txt.open(path);
while(!disparity_txt.eof())
{
disparity_txt >> disparity;
vec_disparities.push_back(disparity);
}
cout << vec_disparities.size() << endl;
disparity_txt.close();
Don't use while(!disparity_txt.eof()) it does not do what you think (eof will only be set after the end of the stream is read, so typically the last iteration is wrong) :
Do :
while(disparity_txt >> disparity)
{
vec_disparities.push_back(disparity);
}
Using while (!in.eof()) is almost always wrong
Either stop looping when extracting a number from the stream fails (as shown in quantdev's answer) or use the standard library facilities meant for populating a container from a stream:
std::ifstream disparity_txt(path);
vec_disparities.assign(std::istream_iterator<int>(disparity_txt),
std::istream_iterator<int>());
You can open an fstream using its constructor, and the destructor will close it, you don't need explicit open and close calls.
In C++11 it's even simpler:
vec_disparities.assign(std::istream_iterator<int>{std::ifstream{path}}, {});
This question already has answers here:
Read a file backwards?
(7 answers)
Closed 8 years ago.
How can I read a text file in reverse order (i.e. from eof) using C++?
Yes, but you basically have to do it manually.
The basic algorithm is as follows:
Seek to the end of the file with is.seekg(0, is.end)
Determine the file size with is.tellg()
Repeatedly seek backwards and read chunks of the file until you reach the front
If the file is small enough so the entire contents easily fit within memory, it will be both far faster and far easier to code to read the file forward into a string and then reversing that string after the fact.
If the contents won't fit in memory, you'll have to use nneonneo's solution. It would probably be best to turn off buffering.
Just use the seekg and related functions in istream class. Here is a working example. Tested.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("file.txt");
// Get the length of the file
in.seekg(0, in.end);
int len = in.tellg();
// Start reading the file in reverse
char c;
while (len--)
{
in.seekg(len, in.beg);
in >> c;
cout << c;
}
}
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
In c++, how can I iterate through each line in a string? There have been plenty of questions regarding reading a file line by line, but how can I do this with a std::string?
For example, if I have the following string:
1051
2232
5152
3821
0021
3258
How would I iterate through each number?
In c++, you can use string exactly as files, using the classes defined in the sstream header:
#include <sstream>
//...
std::string str=...; // your string
std::istrstream in(str); // an istream, just like ifstream and cin
std::string line;
while(std::getline(in,line)){
//do stuff with line
}
This is a bit simplistic, but you get the idea.
You can use in just as you would use cin, e.g. in>>x etc. Hence the solutions from How do I iterate over cin line by line in C++? are relevant here too - you might want to look at them for the "real" answer (just replace cin with your own istream
Edit:
As a side note, you can create strings in the same way you print to the screen, using the ostream mechanism (like cout):
std::ostringstream out;
out << header << "_" << 3.5<<".txt";
std::string filename=out.str();
Use a tokenizer and let '\n' or '\r\n' or the appropriate newline for your OS be the token splitter..
Or if you were using a buffered file stream reader, just create a stringstream from this new string and read from the string stream instead of the file stream.
In short nothing changes except that you aren't reading from a file.
A horribly naive solution would be to make a string stream from this and assign ints or strings in a while loop from it.