Is there any way to skip line breaks while reading a text file?
For example, lets say I have two text files, input.text and output.text.
My input.text file look like this:
welcome to stackoverflow<line break here>
another sentence
.
.
.
I read the first line from input.text and write some part of the line to output.text.
But when I read the second line after the line break, my first line gets lost in the text file.
What should I do?
To read the file I use this code:
ifstream input.open("input.text");
while(input)
{
getline(input,string);
}
and to write
ofstream output;
output<<string;`
Your problem has nothing to do with the enter key and everything to do with how you are reading/writing from the file. Your code apparently looks like this:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string string;
std::ifstream input("input.text");
while (input) { // bad
std::getline(input, string);
}
std::ofstream output("output.text");
output << string;
}
The "while" loop overwrites string for each line. If you had 3 lines of text, at the end of the while loop, string would contain only the last line of the input file.
What you perhaps want to do is something more like:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string string;
std::ifstream input("input.text");
std::ofstream output("output.text");
while (std::getline(input, string)) {
output << string;
}
}
Here is a simpler version using cin and cout:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string string;
while (std::getline(std::cin, string)) {
std::cout << string;
}
}
As written, the "\n" at the end of each line goes missing: http://ideone.com/0FhEyj you can fix this by changing the output line to be
std::cout << string << "\n";
Related
I want to be able to a string that contains certain characters in a file that contains one string per line.
#include <iostream>
#include <fstream>
#include <string>
int main(){
string line;
ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
if(line.find('z')){
cout << line;
}
}
}
That's my attempt at finding all the string that contains the character z.
The text file contains random strings such as
fhwaofhz
cbnooeht
rhowhrj
perwqreh
dsladsap
zpuaszu
so with my implementation, it should only print out the strings with the character z in it. However, it seems to be reprinting out all the contents from the text file again.
Problem:
In your file the strings aren't separated by a space (' ') which is the end delimiter, they are separated by a end of line ('\n'), that is a different character. As a consequence, in the first getline everything goes to line. line contains all the text in the file, including z's, so all the content is printed. Finally, the code exits the while block after running once because getline reaches the end of the file and fails.
If you run this code
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
std::cout << "Hi";
if(line.find('z')){
std::cout << line;
}
}
}
"Hi" will be only printed once. That is because the while block is only executed once.
Additionaly, see that line.find('z') won't return 0 if not match is found, it will return npos. See it running this code (As it says here):
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
std::cout << line.find('z');
if(line.find('z')){
std::cout << line << "\n";
}
}
}
Solution:
Use getline(infile,line) that is more suitable for this case and replace if(line.find('z')) with if(line.find('z') != line.npos).
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
If you need to put more than one string per line you can use the operator >> of ifstream.
Additional information:
Note that the code you posted won't compile because string, cout and ifstream are in the namespace std. Probably it was a part of a longer file where you were using using namespace std;. If that is the case, consider that it is a bad practice (More info here).
Full code:
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::string line;
std::ifstream infile;
infile.open("words.txt");
while(getline(infile,line)){
if(line.find('z') != line.npos){
std::cout << line << "\n";
}
}
}
getline extracts characters from the source and stores them into the variable line until the delimitation character is found. Your delimiter character is a space (" "), which isn't present in the file, so line will contain the whole file.
Try getline(infile, line, '\n') or simply getline(infile, line) instead.
The method find returns the index of the found character, where 0 is a perfectly valid index. If the character is not found, it returns npos. This is a special value whcih indicates "not found", and it's nonzero to allow 0 to refer to a valid index. So the correct check is:
if (line.find('z') != string::npos)
{
// found
}
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 am working on creating a program that is supposed to read a text file (ex. dog, buddy,,125,,,cat,,,etc...) line by line and parse it based on commas. This is what I have so far but when I run it, nothing happens. I am not entirely sure what i'm doing wrong and I am fairly new to the higher level concepts.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
std::ifstream file_("file.txt"); //open file
std::string line_; //declare line_ as a string
std::stringstream ss(line_); //using line as stringstream
vector<string> result; //declaring vector result
while (file_.is_open() && ss.good())
{ //while the file is open and stringstream is good
std::string substr; //declares substr as a string
getline( ss, substr, ',' ); //getting the stringstream line_ and substr and parsing
result.push_back(substr);
}
return 0;
}
Did you forget to add a line like std::getline(file_, line_);? file_ was not read from at all and line_ was put into ss right after it was declared when it was empty.
I'm not sure why you checked if file_ is open in your loop condition since it will always be open unless you close it.
As far as I know, using good() as a loop condition is not a good idea. The flags will only be set the first time an attempt is made to read past the end of the file (it won't be set if you read to exactly the end of the file when hitting the delimiter), so if there was a comma at the end of the file the loop will run one extra time. Instead, you should somehow put the flag check after the extraction and before you use the result of the extraction. A simple way is to just use the getline() call as your loop condition since the function returns the stream itself, which when cast into a bool is equivalent to !ss.fail(). That way, the loop will not execute if the end of the file is reached without extracting any characters.
By the way, comments like //declaring vector result is pretty much useless since it gives no useful information that you can't easily see from the code.
My code:
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
int main()
{
std::ifstream file("input.txt");
std::string line, word;
std::vector<std::vector<string>> result; //result[i][j] = the jth word in the input of the ith line
while(std::getline(file, line))
{
std::stringstream ss(line);
result.emplace_back();
while(std::getline(ss, word, ','))
{
result.back().push_back(word);
}
}
//printing results
for(auto &i : result)
{
for(auto &j : i)
{
std::cout << j << ' ';
}
std::cout << '\n';
}
}
I read line by line of a textfile and if a line meets some requirements I want to override the line and save it at the same position in the same file.
Here is what I have (simplified):
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
fstream file;
string line;
file.open("Test.txt");
while (getline(file, line))
{
if (line.size() > 7) file << line.append(" <- long line");
}
}
You can read your file into memory and then write it out after changing any of the lines. The following example reads it into a vector, then writes it back out.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream file;
string line;
file.open("Test.txt", fstream::in);
if (file.fail()) exit(-1);
vector<string> vec;
while (getline(file, line, '\n'))
{
string ln = line;
vec.push_back(ln);
}
file.close();
// manipulate your lines here
file.open("Test.txt", fstream::out | fstream::trunc);
for (vector<string>::iterator it = vec.begin(); it != vec.end(); ++it)
{
file.write(it->c_str(), it->length());
file.write("\n", 1);
}
file.close();
}
But note, when you change a line, the position of lines that follow will change unless the line you are changing is the same size as the original. Also note, this is a simple ANSI file example, but UNICODE and UTF-8 are also common text file formats. This should at least get you started.
I have a file which contains text. I read line by line of the entire file and append to a string object. But when i get the final string print out i am not getting the whole file content. I am sure it is due to the presence of special characters like '\n', '\r', '\t', etc.
here is my sample code:
// Read lines until end of file (null) is reached
do
{
line = "";
inputStream->read_line(line);
cout<<"\n "<<line;//here i get the content of each line
fileContent.append(line);// here i am appending
}while(line.compare("") != 0);
This is the way to read a file into memory in C++:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
vector <string> lines;
ifstream ifs( "myfile.txt" );
string line;
while( getline( ifs, line ) ) {
lines.push_back( line );
}
// do something with lines
}
You’ll have to show more code for me to know what your problem is.
If you’re reading the entire file into a single string, this is the method I usually use:
#include <string>
#include <fstream>
#include <iterator>
std::string read_file(const char *file_name)
{
std::filebuf fb;
if(!fb.open(file_name, std::ios_base::in))
{
// error.
}
return std::string(
std::istreambuf_iterator<char>(&fb),
std::istreambuf_iterator<char>());
}