Appending strings to text files in C++ - c++

C++ beginner here,
I am trying to append some text to a pre-written .txt file where every line there is a word.
I have been using the method ofstream and ifstream as seen below, but everytime I try to write something, it erases the file. (I am not allowed to use ios:app or simillar)
int append_new_word() {
//First I read everything on the list and save it to a string called Words_in_List
ifstream data_wordlist_in("woerterliste"); //Opens the txt file
if (!data_wordlist_in) // checks if the file exists
{
cout << "File does not exist!" << endl;
return 1;
}
string Word;
int line = 0;
string Vorhandene_Woerter;
std::getline(data_wordlist_in, Wort);
do { //line counter, goes through all lines and save it to a string
line++;
std::getline(data_wordlist_in, Word);
Words_in_List = Words_in_List + "\n" + Word;
} while (!data_wordlist_in.eof());
cout << Words_in_List << endl;
data_wordlist_in.close();
//HEre it should save the string again in the list word per word with the neu appended word
ofstream data_wordlist_out("woerterliste"); //opens ofstream
if (!data_wordlist_out)
{
cout << "File does not exist!" << endl;
return 1;
}
string new_word_in_list;
cout << "\n Insert a Word to append: ";
cin >> new_word_in_list;
data_wordlist_out << Words_in_List << endl << new_word_in_list;
data_wordlist_out.close(); //closes ofstream
}
Everytime I try I open my program it erases the list.

Your code has some minor problems, but nothing that matches your description of it.
It does line based input, which is strange because nothing in the problem description indicates that reading a line at a time is necessary.
It counts lines, again for no obvious reason.
It skips the first line (maybe this is deliberate, but if so you didn't mention that).
The loop termination is incorrect (see link in the comments).
The function is declared as returning an int but no return is made.
Here some code that addresses these problems. It reads characters not lines (using get()) which makes reading the input simpler, but essentially it's the same technique as your code.
void append_new_word()
{
string existing_content;
ifstream in("file.txt");
char ch;
while (in.get(ch))
existing_content += ch;
in.close();
cout << "enter a new word ";
string new_word;
cin >> new_word;
ofstream out("file.txt");
out << existing_content << new_word << '\n';
}

Related

How Do I read and Output the Contents of a File and the Number of Words it Contains?

I am attempting to write a program for homework which reads the contents of a notepad file and displays the contents and the number of words int he file. My code currently outputs nothing when I enter the name of the names of files I am using to test the program, and the input validation while loop I inserted does not function either.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Declare needed variables
string fileName, contents;
int wordCount = 0;
ifstream inData;
//Display program info
cout << "*** A SIMPLE FILE PROCESSING PROGRAM ***" << endl;
//Prompt user input
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
inData.open(fileName.c_str());
//Inform the user when their input is invalid and ask them to input another
file name
while (!inData)
{
inData.clear();
inData.ignore(200, '\n');
cout << "File not found. Please type a correct file name." << endl;
cin >> fileName;
inData.open(fileName.c_str());
}
inData >> contents;
//Read and output the contents of the selected file
while (inData)
{
cout << fileName << " data\n";
cout << "***********************" << endl;
inData >> contents;
wordCount++;
cout << contents << endl;
inData >> contents;
}
//Display the number of words in the file
cout << "***********************" << endl;
cout << fileName << " has " << wordCount << " words." << endl;
inData.close();
return 0;
}
The code compiles in its current state [but does not produce the desired outcome.
I will show you one of the many possible solutions.
But I would not recomend, to check the validity of a filename in a loop. You will give the user no chance to escape. Hence, I propose to open the file, and, if that does not work, show an error message and quit.
Then, what sounds easy in the beginning like, count the words, is not really that easy. What is a word? Characters only, or characters mixed with digits or even an underscore in it like for C++ variable names? Needs to be defined.
Additionally you may have separators like commas or one and more other white spaces. So a line like "Hello,,,,World" cannot be so easily counted. If you try to read the 2 words, then you will see a surprise.
std::string s1{};
std::string s2{};
std::istringstream iss("Hello,,,,World");
iss >> s1 >> s2;
Will read everything in s1!
The solution is that we define clearly what a word is. And this we will do with a std::regex. In the below example we use characters, digits and _
Then we use the regex_iterator to find all occurences of the regex (the word) in the line. We substract the end from the beginning with std::distance, which will give us the count of the words.
Then we give an output to the user in whatever format.
It may seem complicated. But it is precise. And rather flexible. Try to anaylze line by line and you will understand it.
Please see:
#include <iostream>
#include <string>
#include <regex>
#include <fstream>
#include <iomanip>
int main()
{
// Get a filename from the user
std::cout << "Enter a filename:\n";
std::string filename{}; std::cin >> filename;
// Try to open and read the file
std::ifstream fileStream(filename);
if (fileStream) {
// We will count all words
size_t numberOfWordsOverall{ 0 };
// We will also count the lines in the file
size_t lineCounter{ 1 };
// Define, what a word is. In this case: Characters, Digits and _
std::regex regexForWord("[\\w\\d_]+");
// Read all lines in file
std::string line{};
while (std::getline(fileStream, line)) {
// Count the numbers of words in one line
const size_t numberOfWordsInLine = std::distance(
std::sregex_token_iterator(line.begin(), line.end(), regexForWord, 1),
std::sregex_token_iterator()
);
// Update the overall word counter
numberOfWordsOverall += numberOfWordsInLine;
// Show result to user
std::cout << "# " << std::left << std::setw(2) << lineCounter++ << " (Words in line: "<< std::setw(2) << numberOfWordsInLine <<
" Words overall: " << std::setw(4) << numberOfWordsOverall << ") Line content --> " << line << '\n';
}
}
else {
std::cerr << "Could not open file '" << filename << "'\n";
}
return 0;
}
Hope this helps . . .

How to read spaced string with get line() from a file?

I want to read a name like "Penelope Pasaft" all together from a file and save it to a variable "person". I have understood that I have to use the get line(file, person). But I have a problem doing it because I want also to read other variables before.
Imagine a .txt like:
1
+546343864246
Penelope Pasaft
So here is the code:
typedef struct {
string number; //I use string because it is an alphanumeric cellphone number
string person;
int identifier;
} cellphone;
ifstream entry;
entry.open(fileName.c_str());
cellphone c[10];
int j=0;
if(entry)
{
cout << "The file has been successfully opened\n\n";
while(!entry.eof())
{
entry >> c[j].identifier >> c[j].number;
getline(entry,c[j].person);
cout << "Start: " << c[j].identifier << "\nNumber: " <<
c[j].number << "\nPerson: " << c[j].person << endl << endl;
j++;
}
}
Well the problem I have it's that it doesn't seem to print or save me any data to the variable c[j].person
Problem is that your input file has empty lines in it.
If you use cin >> only, it will work OK because >> operator skips blank chars (but stops at blank chars, as you noted: can't have it all)
On the other hand, getline will read the line, even if it's blank.
I propose the following standalone code slightly modified from yours: note the loop until end of file or non-blank line.
(note: it there are spaces only in the line, it will fail)
I also replaced array by a vector, resized on the fly (more C++-ish)
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
typedef struct {
string number; //I use string because it is an alphanumeric cellphone number
string person;
int identifier;
} cellphone;
int main()
{
ifstream entry;
string fileName = "file.txt";
entry.open(fileName.c_str());
vector<cellphone> c;
cellphone current;
int j=0;
if(entry)
{
cout << "The file has been successfully opened\n\n";
while(!entry.eof())
{
entry >> current.identifier >> current.number;
while(!entry.eof())
{
getline(entry,current.person);
if (current.person!="") break; // stops if non-blank line
}
c.push_back(current);
cout << "Start: " << c[j].identifier << "\nNumber: " << c[j].number << "\nPerson: " << c[j].person <<endl<<endl;
j++;
}
}
return 0;
}
output:
The file has been successfully opened
Start: 1
Number: +546343864246
Person: Penelope Pasaft

regarding: instance of 'std::bad_alloc'

I read other posts but none of them helping at all,
This code have no error still there is bad_alloc error...
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "\n\nReading from file \n\n" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
This code is terminating after coming to sentence statement..the getline() function is causing problem i guess but when i tried on other two statements(name and last_name),the getline(), it works perfectly..i even degraded the char limit to 5 too but after sentence statement is throw anyways
Thumb rule, don't fool yourself into thinking that your code has no errors. Especially when you clearly got an error. This kind of mindset will make you unable to find errors because everything you see is correct.
You never checked if your streams were open and you entered the wrong file name in the ofstream.
What happens is that, you write your data into a file name farses.dat and then you try to open a file called frases.dat (which I assume is the correct name, it means sentences).
You are getting the cursor position ifstream::tellg of an inexistent file, and it fails so the function returns -1. This is the value of length before you allocate your buffer.
When you do allocate your buffer you get a bad_alloc exception (bad_array_new_length).
Checking if your file was open would, at the very least, have saved you some debug time.
Something like this,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
EDIT: Fixed error explanation.

Counting lines from a file input?

The following code is supposed to count: the lines, the characters and the words read from a text file.
Input text file:
This is a line.
This is another one.
The desired output is:
Words: 8
Chars: 36
Lines: 2
However, the word count comes out to 0 and if I change it then lines and characters come out to 0 and the word count is correct. I am getting this:
Words: 0
Chars: 36
Lines: 2
This is my code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream inFile;
string fileName;
cout << "Please enter the file name " << endl;
getline(cin,fileName);
inFile.open(fileName.c_str());
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
while( getline(inFile, line) )
{
number_of_lines++;
number_of_chars += line.length();
}
string words;
int number_of_words = 0;
while (inFile >> words)
{
number_of_words++;
}
cout << "Words: " << number_of_words <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}
Any guidance would be greatly appreciated.
And because Comments are often unread by answer seekers...
while( getline(inFile, line) )
Reads through the entire file. When it's done inFile's read location is set to the end of the file so the word counting loop
while (inFile >> words)
starts reading at the end of the file and finds nothing. The smallest change to the code to make it perform correctly is to use seekg rewind the file before counting the words.
inFile.seekg (0, inFile.beg);
while (inFile >> words)
Positions the reading location to file offset 0 relative to the beginning of the file (specified by inFile.beg) and then reads through the file to count the words.
While this works, it requires two complete reads through the file, which can be quite slow. A better option suggested by crashmstr in the comments and implemented by simplicis veritatis as another answer requires one read of the file to get and count lines, and then an iteration through each line in RAM to count the number of words.
This has the same number of total iterations, everything must be counted one by one, but reading from a buffer in memory is preferable to reading from disk due to significantly faster, orders of magnitude, access and response times.
Here is one possible implementation (not tested) to use as a benchmark:
int main(){
// print prompt message and read input
cout << "Please enter the file name " << endl;
string fileName;
getline(cin,fileName);
// create an input stream and attach it to the file to read
ifstream inFile;
inFile.open(fileName.c_str());
// define counters
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
vector<string> all_words;
do{
getline(inFile, line);
// count lines
number_of_lines++;
// count words
// separates the line into individual words, uses white space as separator
stringstream ss(line);
string word;
while(ss >> word){
all_words.push_back(word);
}
}while(!inFile.eof())
// count chars
// length of each word
for (int i = 0; i < all_words.size(); ++i){
number_of_chars += all_words[i].length();
}
// print result
cout << "Words: " << all_words.size() <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}

Using getline to read from file to a 2d string array

I am trying to read the contents of a text file into a 2D string array, but no matter what I have tried or searched, I can not find a solution. The code is supposed to load a text file separate it into elements by finding horizontal tabs and display the output. When I run the code as is, I receive an error that I found out from searching online, means that I'm trying to manipulate memory I shouldn't be. I'm not asking for the code to be written, just a push in the right direction. Thank you in advance.
this is what I get when I run the program:
0x23fd5c
Process returned -1073741819 (0xC0000005) execution time : 2.344 s
Press any key to continue.
EDIT:: I have corrected the code so it now functions as it should, but it is not storing the last entry of each line in the text file correctly. I can somehow display the number 100 which is the last entry, but when I try to pass that location or display just playList[0][5] , it says it is equal to the first entry of the next line. Any help would be amazing I posted the current code below.
here is my code:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
void readTextFile( int &Count, string playList[50][5]);
void userAddition( int &Count, string playList[50][5]);
int main()
{
string decision;
string playList[50][5];
int Count = 0;
readTextFile(Count, playList);
cout << "If you would like to add to the list, Please enter 'Y'. If you would like to exit
please enter 'N'. ----> ";
getline(cin, decision);
if (decision=="y" || decision=="Y")
userAddition(Count, playList);
else
{
return(0);
}
return 0;
} // End of Main FN.
void readTextFile( int &Count, string playList[50][5])
{
string inputfield;
ifstream infile("c:\\cTunes.txt", ifstream::in);
if ( infile.is_open() )
{
// File is read.
} // end if
else
{
cout << "Error Opening file" << endl;
return; //Program Closes.
} // end else
cout << setw(30)<<left<< "TITLE"<< setw(10) <<left<<"LENGTH"<<
// Outputs a title to each column that is displayed.
setw(40)<< left<<"ARTIST"<< setw(40) << left<<"ALBUM"<<
setw(15) << left <<"GENRE" << setw(5) << left << "RATING" << endl;
getline(infile, inputfield, '\t'); // read until tab
while(! infile.eof()) // loop until file is no longer valid.
{
playList[Count][0] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][1] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][2] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][3] = inputfield;
getline(infile, inputfield, '\t'); // read until tab.
playList[Count][4] = inputfield;
getline(infile, inputfield); // read until end of line.
playList[Count][5] = inputfield;
cout << setw(30)<<left<< playList[Count][0] << setw(10) <<left<<playList[Count][1] <<
// Output the line number equal to count.
setw(40)<< left<<playList[Count][2] << setw(40) << left<< playList[Count][3] <<
setw(15) << left << playList[Count][4] << setw(5) << left << playList[Count][5] <<
endl;
/*cout <<"Title: " << setw(25)<<left<< playList[Count][0]<<endl;
cout <<"Length: " << setw(5) <<left<<playList[Count][1] << endl;
cout <<"Artist: " << setw(50)<< left<<playList[Count][2] << endl;
cout <<"Album: " << setw(40) << left<< playList[Count][3] << endl;
cout <<"Genre: " << setw(15) << left << playList[Count][4] << endl;
cout <<"Rating: " << setw(5) << left << playList[Count][5] << endl<<endl;*/
Count++; // Increment counter by 1
getline(infile, inputfield, '\t'); // read next line until tab.
} // end while
infile.close(); // close the file being read from.
cout<<endl<<endl<<playList[0][5]<<endl;
} // End of readTextFile
I believe getline is causing the problem when reading till the end of the line but I'm truly at a loss.
First, note that in the following line:
cout << playList << endl;
you are printing the address of the array, not the contents. you will need
a loop to print the contents.
Second, in the following code:
if ( infile.is_open() )
{
// ok, read in the file
} // end if
else
{
cout << "Error Opening file" << endl;
//a return statement is missing
}
you need a return statement to avoid reading from a closed stream (which can cause a crash)
Finally, your function does not return anything, so it should either be declared void
or return some value (in which there is no sense according to the context).
Hope that helps and good luck!
The readTextFile function does not return anything. You need to return a string. If you are getting the error what(): basic_string::_S_construct null not valid then this is your problem. You can avoid similar problems by using -Wall compiler option.
You are using std::string for storing the string, std::ifstream for reading from a file, std::getline for reading words... you should really use std::vectors instead of arrays:
typedef std::vector<std::string> Line;
std::vector<Line> playList;
It will make things easier for you.
I also recommend you to change the way you read from a file to:
while(getline(...))
{
...
}
But since you are not allowed to use std::vector, your function could look like this:
// reads the content of input file and stores it into playList:
void readTextFile(std::ifstream& infile, std::string playList[][5])
{
std::string line;
for (int lineIndex = 0; getline(infile, line); ++lineIndex)
{
// skip empty lines:
if (line.empty()) continue;
std::string word;
std::istringstream lineStream(line);
for (int wordIndex = 0; getline(lineStream, word, '\t'); ++wordIndex)
{
// skip empty words:
if (line.empty()) continue;
playList[lineIndex][wordIndex] = word;
}
}
}
that could be used like this:
std::string playList[19][5];
std::ifstream infile("c:\\Test.txt");
if (infile.is_open())
{
readTextFile(infile, playList);
infile.close();
}
else
std::cout << "Error Opening file" << std::endl;
Also note that cout << playList << endl; outputs the address of the first word. To print all words, you will have to write a loop.