I don't understand why my ifstream can not be read in my class. In the main.cpp reading from the stream works fine, but when I pass the ifstream by reference to the c'tor I am not able to read from it. The program compiles fine but the 'inputfile' seems to be empty. In the console, I just see the content of my .txt once which comes from the main.cpp.
Am I doing something wrong with passing the ifstream?
main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "RAM.h"
int main(int argc, char** argv)
{
std::ifstream input;
input.open("\\path\\orders.txt");
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
RAM machine(input);
}
RAM.h:
#pragma once
#include <fstream>
class RAM
{
private:
std::ifstream& inputfile;
public:
RAM(std::ifstream&);
~RAM();
};
RAM.cpp:
#include "RAM.h"
#include <iostream>
#include <fstream>
#include <string>
RAM::RAM(std::ifstream &in) : inputfile(in){
std::string line;
while (std::getline(inputfile, line))
{
std::cout << line << std::endl;
}
}
RAM::~RAM() {
}
orders.txt:
ADD 5
SUB 7
HLT 99
The input file appears to be empty since you have already read all the data in main(). In other words, you're at the end of the file:
// File just opened, at position 0.
std::string line;
while (std::getline(input, line))
{
std::cout << line << std::endl;
}
// File fully read, at end of file.
RAM machine(input);
If you want to re-read it, you'll need to seek back to the start before attempting to re-read in the constructor, something like:
inputfile.seekg(0);
Related
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
ifstream in ("input.txt");
ofstream out ("output.txt");
int main(){
char collection [30];
while ( in.good() ){
in >> collection;
}
cout << collection[0] <<endl;
in.close();
out.close();
return 0;
}
I'm trying to read a text file in C++ programming.But it certainly is not working since it doesn't print anything. It's just a single line containing some operands. Can someone help me out?
Put those definitions of in and out inside main. Don't create global variables unless you absolutely have to.
The code loops through the input, and overwrites the contents of collection each time through the loop. When it reaches the end of the input, it writes out the first character in collection. It should either display what it read each time through the loop, or add each string that it reads into a container. If it's the former, the code would look like this:
#include <fstream>
#include <iostream>
int main() {
std::ifstream in("input.txt");
std::string input;
while (in >> input)
std::cout << input << '\n';
return 0;
}
Note that the original code didn't use out, so I left it out here. Also, when in is an auto object (i.e., defined inside main), when main returns it gets destroyed. One of the things that the destructor does is close the file, so there is no need to call in.close();.
If you want to put the input into some kind of collection, that's a straightforward change:
#include <fstream>
#include <iostream>
#include <vector>
int main() {
std::ifstream in("input.txt");
std::string input;
std::vector<std::string> collection;
while (in >> input) {
collection.push_back(input);
std::cout << input << '\n';
}
std::cout << "Contents of collection:\n";
for (auto& x : collection)
std::cout << x << '\n';
return 0;
}
If you want to write the text to an output file, just do it:
#include <fstream>
int main() {
std::ifstream in("input.txt");
std::ofstream out("output.txt");
std::string input;
while (in >> input)
out << input << '\n';
return 0;
}
That will write each word from the input onto a separate line in the output file. If you just want to copy the file unchanged, that's even easier:
#include <fstream>
int main() {
std::ifstream in("input.txt");
std::ofstream out("output.txt");
out << in.rdbuf();
return 0;
}
I am trying to write and read information from the same file, but I don't know actually how to do that and why it doesn't work.
When I compile the code, the string that I expect to be filled with information from the file, actually doesn't get filled.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
ifstream fin("Asort.txt");
ofstream fout("Asort.txt");
fout << "hello world";
getline(fin, str);
cout << str;
}
The problem is the location of the "cursor" (thus: the marker) after the statement:
fout << "hello world";
Illustration:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
ifstream fin("Asort.txt");
ofstream fout("Asort.txt");
fout << "hello world"; //output to cout this statement(fout.tellp()) to see where the marker is at this point in the stream
fout.seekp(0); //reset the marker in the fout stream to the beginning
getline(fin, str);
cout << str;
}
The cursor is now at the end of the stream. So you have to use:
fout.seekp(0);
to get it to the beginning so that the fin can start reading from the beginning of the stream.
I was wanting to know if there was a simple way to set a std::string equal to the contents of a file in C++. So far, I was thinking something like this: (although I haven't tested it, so I don't know if it will work)
#include <fstream>
#include <string>
int main(int argc, char *argv[]){
fstream in("file.txt");
string str;
str = in;
return 0;
}
Is this a way to accomplish this? If not, is there a simple way to do so? Thanks!
Here is one possible solution using vector<string>, each element is a line.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// vector that will store all the file lines
vector<string> textLines;
// string holding one line
string line;
// attach input stream to file
ifstream inputFile("data.txt");
// test stream status
if(!inputFile)
{
std::cerr << "Can't open input file!\n";
}
// read the text line by line
while(getline(inputFile, line))
{
// store each line as vector element
textLines.push_back(line);
}
// optional (stream object destroyed at end of function scope)
inputFile.close();
return 0;
}
There is a standard way:
std::ifstream file("myfilename.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content( buffer.str() );
References
http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt specially item (8)
try this one
#include <fstream>
#include <cstdlib>
std::string readText(const char* fileName)
{
std::ifstream file(fileName);
if (!file.good())
{
std::cout << "file fail to load..." << fileName;
exit(1);
}
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
I think i have a beginners question.
I try to read a file line by line.
The file is in /home/myhomedir and called text.txt .
The content of the file is
1
2
3
4
The file has access right for everyone to read and write.
I wanted: open the file and read it one line after another.
So I tried:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/myhomedir/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
// do nothing, just get a line
// *
}
}
}
catch(int ex)
{
}
return 0;
}
The place marked with * is reached (used the debug feature of netbeans). however line is empty and loop seemed to be entered only once.
Like if an empty file is opened.
What am I doing wrong?
The reason is, you don't know how to use debugger. I've modified your code:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
try
{
ifstream myfile ;
myfile.open("/home/enedil/text.txt", ios::in);
if(myfile.is_open())
{
string line;
while (getline(myfile, line)) {
cout << line; // there's my modification
}
}
}
catch(int ex)
{
}
return 0;
}
The output is
1234
So everything's correct.
If the content of the file is literally
1 2 3 4
then it has only one line and it is to be expected that "getline" returns false the second time it's called.
I have this .txt file that has a lot of words ( one each line ).
I tried
ifstream myReadFile;
myReadFile.open("restrict_words.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
printf("mamao");
myReadFile >> output;
cout<<output;
}
}
But i dont know how to make it work like... where should i pass it path and stuff
I would like to do
while(reading){
stringArray.add(file.line);
}
How can i do that?
First, this: (!myReadFile.eof()) is wrong. See the link for why. Second. If all you want is to load a file of strings into an array, this will do it:
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::ifstream inp("restrict_words.txt");
std::istream_iterator<std::string> inp_it(inp), inp_eof;
std::vector<std::string> words(inp_it, inp_eof);
// words now has ever whitespace separated string
// from the input file as a vector entry
for (auto s : words)
std::cout << s << '\n';
}
Suggested reading:
std::vector<>
std::string
std::istream_iterator<>
C++11 Range-based for loop
Do you mean this?
//untested
#include <vector>
#include <fstream>
#include <string>
#include <iostream> //edited
int main()
{
std::ifstream ist("restrict_words.txt");
std::string word;
std::vector<std::string> readWords;
while(ist >> word)
readWords.push_back(word);
//test
for(unsigned i = 0; i != readWords.size(); ++i)
std::cout << readWords.at(i) << '\n'; // or readWords[i] (not range checked)
}
EDIT:
For each individual line you would do:
std::string line;
std::vector<std::string> readLines;
while(std::getline(ist, line))
{
readLines.push_back(line);
}