Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi i am trying to pass a whole file into a string. This is my Code but the program is always exiting on the first if(). I just can't get behind what i am doing wrong here.
#include <iostream>
#include <fstream>
#include <string>
std::string readFile (std::string filename);
int main() {
std::string filename;
std::string Eingabestring;
std::cout << "Geben Sie eine Datei an" << std::endl;
std::cin >> filename;
Eingabestring = readFile(filename);
std::cout << Eingabestring << std::endl;
return 0;
}
std::string readFile (std::string filename)
{
std::string zeile,inhalt ;
std::ifstream quelle;
quelle.open(filename.c_str());
if (!quelle)
{
std::cerr << filename << " kann nicht geöffnet werden!\n";
return exit(-1);
}
while (!quelle.eof())
{
getline(quelle,zeile);
inhalt = inhalt + zeile;
}
return inhalt;
}
Already thanks for your help!
Edit: I just noticed that i put the file into a wrong folder.. But the code still isn't reading the whole file. Just the first line, but i thought with the loop i could get every line of my file into the string?
And i fixed the second return 0 to exit(-1). Thats better right?
Other than checking to see why the open() failed as explained in the comments also keep in mind that there are easier ways to check for when you have hit the end of file in a while loop where you are reading from an istream.
The idiomatic way to loop and read from an istream in C++ is to embed the read expression that returns a reference to the istream in the loop condition, so change your code to
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
auto character = char{};
auto file_string = string{};
while (cin.get(character)) {
file_string += character;
}
cout << file_string << endl;
return 0;
}
I've used cin above but just replace cin with your file stream object and everything should work normally.
Note that the while terminating condition is now an istream reference, and that is convertible to bool, so the loop will exit when the istream object is done reading or when the stream encounters any errors besides EOF. You don't have to check for eof() yourself.
Also another thing is to pass strings that you do not intend to modify by const reference instead of by value, so the readFile() function should accept a const string& instead of a string, this will help save you string copying. When C++17 is available replace that const string& with std::string_view
Try something like this to read your file instead:
std::string readFile (std::string filename)
{
std::ifstream quelle(filename);
std::string content( (std::istreambuf_iterator<char>(quelle) ),
(std::istreambuf_iterator<char>()) );
return content;
}
Related
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//reading the text file
ifstream inputFile("testfile1.txt");
inputFile.open("testfile1.txt");
while(!inputFile.eof())
//eof till end of file, reads the txt till end of file
{
string str;
getline(inputFile,str);
cout <<str<< endl;
}
inputFile.close();
return 0;
}
// The problem that i am having is that it doesn not read the file or anything in it. Doing nothing it says Program ended with exit code: 0. Could anyone check the mistake in the code
First Bug: You are opening the input file twice. Per the C++ standard, regarding the behavior of your second open request (the direct call to the open member):
C++11 § 27.9.1.9 [ifstream.members/3]
void open(const char* s, ios_base::openmode mode = ios_base::in);
Effects: Calls rdbuf()->open(s, mode | ios_base::in). If that function
does not return a null pointer calls clear(), otherwise calls
setstate(failbit) (which may throw ios_base::failure (27.5.5.4)).
which therefore asks the question, what does rdbuf()->open(...) do ? Well, a std::ifstream uses a filebuf for it's buffering, and once again, per the standard:
C++11 §27.9.1.4 [filebuf.members/2]
basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);
Effects: If is_open() != false, returns a null pointer. Otherwise, initializes the filebuf as required. ...
In short, your double-open is putting your stream into a fail-state, which means all data-related operations with it are going to fail outright from that point on.
Second Bug: Improper use of .eof in a loop conditional expression. you'll run into this once you fix the first bug. The reasons this is not being done correctly are explained in the following question far better than I can explain it here.
Why is iostream::eof inside a loop condition considered wrong?
Suffice it to say, check your IO operations, not just the eof-state of the stream. Get into that habit and stick with it.
Fixing both, your code can literally be reduced to simply this:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream inputFile("testfile1.txt");
std::string str;
while (std::getline(inputFile, str))
std::cout << str << std::endl;
}
Obviously if you're shooting for more robust code, you probably want to perform some error handling in there, something like:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
std::ifstream inputFile("testfile1.txt");
if (!inputFile)
{
std::cerr << "Failed to open file\n";
return EXIT_FAILURE;
}
std::string str;
while (std::getline(inputFile, str))
std::cout << str << std::endl;
}
This is the correct way to read a file according to this article!
The problem in your code it seems that you are using an IDE and it cannot find the path you are giving to ifstream so try to give a full path to the file. Hope it can help u.
string line;
ifstream f("/YOUPARTH/testfile1.txt");
if (!f.is_open())
perror("error while opening file");
while(getline(f, line)) {
cout << line << endl;
}
if (f.bad())
perror("error while reading file");
return 0;
Translate the while statement: "While inputFile is at End Of File" .. you want the negation of that.
I have some code here
https://github.com/Fallauthy/Projects/blob/master/cPlusPlusProjects/bazaPracownikow/bazaPracownikow/bazaPracownikow/main.cpp
And I have no idea how to show contents in my file. I mean i know how, but it doesn't show same I Have in file (in link). It show in next line. This code is responsible to load file
while (!baseFile.eof()) {
//wczytaj zawartosc pliku do zmiennej
std::string buffer;
baseFile >> buffer;
//wypisz
loadLineFromBase += buffer;
loadLineFromBase += " \n";
}
std::cout << loadLineFromBase << std::endl;
Unless I see all your code all I can do for you is give you a sample in return, I don't know what you're trying to do but it seems in this case you're looking for this.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string Display = "";
ofstream FileOut;
ifstream FileInput;
FileOut.open("C:\\Example.txt");
FileOut << "This is some example text that will be written to the file!";
FileOut.close();
FileInput.open("C:\\Example.txt");
if (!FileInput)
{
cout << "Error File not Found: " << endl;
return 1;
}
while (!FileInput.eof())
{
getline(FileInput, Display);
}
FileInput.close();
cout << Display << endl;
return 0;
}
Simply put if you're currently working wit ha text document
use getline()
When you use getline() it takes two arguments the first will be in this case your ifstream object, as in what you're using to open the file. The second will be the string you're using to store the contents in.
Using the method I outlined above you'll be able to read the entire file contents.
And please next time as it was said above outline your problem more in depth and if you provide us with all of your code we may better assist you!
Your snippet of code automatically add a newline to every string read from the input file, even if originally those were words separeted by spaces. Probably you want to keep the structure of the original file, so it's better to read one line at a time and, unless you need it for some other uses, print it out in the same loop.
std::string buffer;
// read every line of baseFile till EOF
while ( std::getline(baseFile, buffer) ) {
std::cout << buffer << '\n';
}
Here is what I got so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int characterList = 0;
char* dynamo = new char[1000];
char* buffer = dynamo;
ifstream input("wordlist.txt");
if (input.is_open())
{
input >> dynamo[characterList];
while (input.eof())
{
characterList++;
input >> dynamo[characterList];
cout << dynamo[characterList];
}
}
else
{
cout << "File not opened" << endl;
}
return;
}
I'm a beginner so I do apologize if this looks like terrible coding practice. I created a text file with a quote from Bill Cosby that I'm trying to read one word at a time. The quote is "I don't know the key to success, but the key to failure is trying to please everybody." I'm trying to read one word at a time from a text document ignoring punctuation. I know there are a lot of questions similar to this, but they are using code that I have not learned so I'm sorry for having a repeating question. I have not learned getline (I used cin.getline) and #include <string>.
Edit: I forgot to mention, so I'm sorry for not doing so earlier, but I'm studying dynamic memory allocation which is why I'm using the new char[1000].
I'd suggest you to use std::string instead of manually allocating buffers on the heap with new[] and trying to read text manually from the file into those buffers (and don't forget to free the buffer with proper delete[] calls!).
C++ input stream classes like std::ifstream can simply read text into std::string instances thanks to a proper overload of operator<<.
The syntax is as simple as:
string word;
while (inFile >> word)
{
cout << word << endl;
}
Here's a complete compilable sample code for you to experiment and learn:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream inFile("test.txt");
if (inFile.is_open())
{
string word;
while (inFile >> word)
{
cout << word << endl;
}
}
else
{
cout << "Can't open file." << endl;
}
}
This is the output I got on a test text file having the content specified in your question:
I
don't
know
the
key
to
success,
but
the
key
to
failure
is
trying
to
please
everybody.
NOTE
Of course, once you have your words read into a std::string instance, you can store them in a container like std::vector<std::string>, using its push_back() method.
I would do something like this:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string array[6];
std::ifstream infile("Team.txt");
std::string line;
int i = 0;
while (std::getline(infile, line)) {
array[i++] = line;
}
return 0;
}
based on this answer.
Here, we assume we have to read 6 lines from the file "Team.txt". We use std:::getline() and we put inside a while so that we read all the file.
At every iteration, line holds the current line of the file read. Inside the body we store it in array[i].
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am very new to C++ i have this code which is supposed to print the text file in Task1 but it displays nothing and it gives me no output. and the text file contains "1 2 3 4" for an example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line );
//cout<<line.length();
while( getline( myfile, line ) )
{
for (int i=0; i < line.length(); i++)
{
cout<<line[i];
//if (line[i] ...) // look at each character and process it accordingly
}
}
getchar();
}
how can i fix this?
There is a simple issue with your code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line ); // That's the problematic line!
//cout<<line.length();
while( getline( myfile, line ) ) // first line lost here
...
You read the first (and presumably only line) of the file and simply discard it, because you enter the while loop immediately afterwards.
Fix: Remove the line getline( myfile, line ); that precedes the while loop.
You should also check that the file actually exists (there may be a typo in the filename!):
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
if ( !myfile )
{
std::cerr << "File does not exist!\n";
return 1;
}
If you aren't planning to use the fstream for output as well, just replace
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
by
std::ifstream myfile("D:\\Task1.txt");
You are ignoring first line by reading and do not outputting it.
string line ;
ifstream myfile("D:\\Task1.txt");
while(getline(myfile, line))
{
cout << line << endl;
}
Extra:
You don't need to use std namespace if you are using "using namespace std".
You can use ifstream to read-only.
Better You use ifstream for reading.
Check always an ifstream, whether the open was successful or not.
std::ifstream myfile("D:\\Task1.txt");
if( !myfile.is_open() ) {
cerr << "error open file\n";
// return or break
}
If You want to read numbers, so read numbers
for( int number; myfile >> number; ) {
cout << number << endl;
}
you need to flush the cout if you want the output printed. Change this line:
cout<<line[i] << std::endl;
and you will have the chars printed in a column
How many lines you have in text file?
You call getline twice before you start printing output. If you have only one line you'll get empty string ;)
Also I don't think your while condition is proper. Getline won't return anything useful anyway (it returns istream). If it approach end of file it'll simply rise error flag.
You should do it like that:
while (! myfile.eof() )
{
// do some reading & printing
}
Also, please, remember to close your file via myfile.close().
Hope it helps.
I'm creating this simple program which would save me alot of time, but I'm kinda stuck.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> tempfile;
string line;
ifstream oldfile("old.lua");
if (oldfile.is_open())
{
while (oldfile.good())
{
getline(oldfile, line);
tempfile.push_back(line + "\n");
}
oldfile.close();
}
else
{
cout << "Error, can't find old.lua, make sure it's in the same directory as this program, and called old.lua" << endl;
}
ofstream newfile("new.lua");
if (newfile.is_open())
{
for (int i=0;i<tempfile.size();i++)
{
for (int x=0;x<tempfile[i].length();x++)
{
newfile << tempfile[i][x];
}
}
newfile.close();
}
return 0;
}
So, what this does now, is just copies a file. But I've tried to do it, so it changes fe. every "function" word to "def", I've tried everything and googled already, couldn't find anything useful enough, only thing I found was using sstream, but it didn't work after all, or maybe I'm just not skilled enough to do it, so if anyone could give me any tips or help, cause I really am stuck? :d
boost has a replace all function, and it's much more efficient than the naive search-replace-repeat algorithm. This is what I would do:
std::string file_contents = LoadFileAsString("old.lua");
boost::replace_all(file_contents, "function", "def");
std::ofstream("new.lua") << file_contents;
LoadFileAsString is my own function that looks something like this:
std::string LoadFileAsString(const std::string & fn)
{
std::ifstream fin(fn.c_str());
if(!fin)
{
// throw exception
}
std::ostringstream oss;
oss << fin.rdbuf();
return oss.str();
}
http://www.boost.org/doc/libs/1_33_1/doc/html/replace_all.html
I didn't really understand your problem. I think you need to edit your post and ask it clearly.
But still you can do one major improvement in your code. You should be reading file using C++ stream, in this way:
while (getline(oldfile, line))
{
tempfile.push_back(line + "\n");
}
which is more idiomatic way of reading file using C++ stream!
Read this excellent blog by #Jerry Coffin (an SO user) :
http://coderscentral.blogspot.com/2011/03/reading-files.html
EDIT:
You want to find and replace text in your file, then see the accepted answer in this topic:
String Replace in C++
Try this http://www.boost.org/doc/libs/1_46_1/libs/regex/doc/html/boost_regex/ref/regex_replace.html , http://www.cppreference.com/wiki/string/basic_string/replace