How to add multiple lines to a file in C++? - c++

I am new to C++ and write a little todo list on the console.
I am only able to add one line to a text file but when I try to add more it just won't appear on my text file.
Please take a look what I am doing wrong
//output-file stream
ofstream file;
file.open("output.txt", std::ios_base::app); //append
bool isRunning = true;
while (isRunning) {
cout << "Please select an action:" << endl;
cout << "add - adding tasks to the list" << endl;
cout << "del - deleting tasks to the list" << endl;
cout << "list - show the list" << endl;
cout << "x - to exit program" << endl;
string input;
cin >> input;
string addedTask;
if (input == "add") {
cout << "Please enter a task you like to add: " << endl;
cin.ignore();
if (std::getline(std::cin, addedTask)) {
file << addedTask << "\n";
}
else {
cout << "Failed to read line" << endl;
}
}
Why can I only add one string line? I still can't figure out the problem or am I missing something?

Did you try replacing your
file << addedTask << "\n";
by
file << addedTask << endl;
I think it should work (for me it's working)

Related

How to remove certain lines when reading FASTA files?

I'm trying to read in the database down below into a vector of strings while removing the header lines (lines with >db) and imputing each sequence below it into a string.
This is the code I have right now:
void read_in_database_file(string db_file) {
ifstream fin;
fin.open(db_file);
if (!fin.is_open())
{//if
cerr << "Error did not open file" << endl;
exit(1);
}//if
vector<string> database;
string line = "";
while(getline(fin, line, '>'))
{
database.push_back(line);
}
finding_kmers(database);
}
int main() {
cout << "\n" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "------------------------------------ BLAST -----------------------------------" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << endl;
cout << "Welcome to BLAST" << endl;
cout << "Please enter the name of your datafile" << endl;
string db_file = "";
getline(cin, db_file);
cout << endl;
read_in_database_file(db_file);
}
Currently, all it does is simply remove the ">" but print that line and everything else as is. How do i solve this?
database file:
>db_1
GATCTTGCATTTAGAAAATCATAAGAAATTTACTAAAAAGTATTAGGACTCATGAACAAATTTAAGAATG
TAACACTATATAAGATTGGTATACAAAAATAACTGTACTTCTTCACCAAGAAATCAAGAATCCAAAAATG
>db_2
TAGTTTGTTCTAGGATTTATGTGTTTCCTTAAAGTCTTAGTTTGATTATGTTACATTTAGCATGAGTGAC
TCCATTTTGGTTTGGTTTGGTCTGTTGGGACCTATTGCATGAGTTTAGTTCAAAACAATGGCCTCCCATA
>db_3
TTGTCCTTGCGATAGTTTACTGAGAATGATGATTTCCAATTTCATCCATATCCCTACAAAGGACATGAAC
TCATCATTTTTTATGGCTGCATAGTATTCCATGGTGTATATGTGCCATAATTTCTCAATCCAGTCTATCG

Searching for artist name and song from a file in C++

I have written some code for the search function in C++ to find artist name and song. My code doesn't seem to work. A message displays that the artist and song is found and then the menu repeats itself infinite times.
My full program code is as below.
#include "Music.h"
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void Music::menu()
{
int input;
do {
cout << "Select an option from the menu" << endl;
cout << "1. Display records" << endl;
cout << "2. Search for records" << endl;
cout << "3. Writing records to a file" << endl;
cin >> input;
switch (input) {
case 1:
displayfile();
break;
case 2:
searchrecords();
break;
case 3:
writefile();
break;
default:
cout << "Invalid option entered. Try again" << endl;
menu();
}
} while (input != 4);
}
void Music::displayfile()
{
string line;
ifstream myfile;
myfile.open("Music.txt");
if (myfile.is_open()) {
while (getline(myfile, line)) {
cout << line << endl;
}
myfile.close();
}
else {
cout << "Unable to open file" << endl;
}
}
void Music::writefile()
{
ofstream write;
write.open("Music.txt", ofstream::app);
if (write.is_open()) {
cin.ignore();
cout << "Enter a title of song to the playlist" << endl;
cin.getline(title, 255).get();
write << " " << title;
cout << "Enter the artist of the song to playlist" << endl;
cin.getline(artist, 255).get();
write << " " << artist;
cout << "Enter the year of the song" << endl;
cin >> year;
write << "" << year;
cout << "Enter the duration of the song" << endl;
cin >> duration;
write << " " << duration;
cout << "Writing to a file is successful" << endl;
}
else {
cout << "File couldn't be open" << endl;
}
write.close();
displayfile();
}
bool Music::searchrecords()
{
bool found = true;
string search;
string line;
ifstream myfile;
myfile.open("Music.txt");
cout << "Enter the artist you want to search for: " << endl;
getline(cin, search).get();
cout << "Enter for the song you want to search for: " << endl;
getline(cin, search).get();
if (myfile.is_open()) {
while (!myfile.eof()) {
if (found) {
cout << "The artist is found" << search << endl;
cout << "The song is found" << search << endl;
return found;
}
else {
cout << "The artist is not found" << endl;
return false;
}
getline(myfile, line);
myfile.close();
displayfile();
}
}
}
Appreciate it if you could help me as I am stuck on what to do.
You have bool found = true; right in the beginning of Music::searchrecords function, so the first iteration of looking through file immediately returns.
You do getline(cin, search).get(); twice in a row, while apparently you want to read in two different string variables, one for artist, one for song
You do a loop with this if on each iteration
if (found) {
cout << "The artist is found" << search << endl;
cout << "The song is found" << search << endl;
return found;
}
else {
cout << "The artist is not found" << endl;
return false;
}
In both cases you terminate your function by calling return, so the very first iteration of looking through file returns from function (you don't read the file completely)
You call
myfile.close();
displayfile();
on each iteration, so even if you hadn't had your if right above, then your program would crash anyway, because you close file inside the loop that's iterating over it.
You don't compare line to check if you indeed found your song
In total, your program doesn't work at all, and StackOverflow isn't a forum to completely write the entire program instead of you. So you better use a debugger in your IDE to see what your program does step by step, or take a piece of paper and a pen to write down how you would accomplish your task

Selecting random words from an generating a sentence from an input file

I need to create a program that has 4 columns of words from an input file.
then randomly selects a word from each column and generates a sentence. The ultimate goal is to have a conversation that gets saved to the output file.
I've already created the code that reads the input file, and opens the output file to write on but i'm not sure how to select a word from a column and create the sentence, i'm guessing using an array would work but i'm not certain how to connect it with the file?
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string ifilename, ofilename, line;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
cout << "Hi, what's up? " << endl; // Pre-set opener
while (getline(inFile, line))
{
cout << line << endl;
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
You can use a 2D vector of strings to store the words of the sentences and use a random number generator like rand to pick a particular row element from every column. Something like the following
vector<vector<string>> myConversationVector;
while (choice != "no")
{
std::cout << myConversationVector[rand() % 5][0] <<" "
<< myConversationVector[rand() % 5][1] <<" "
<< myConversationVector[rand() % 5][2] <<" "
<< myConversationVector[rand() % 5][3];
}

Trouble while writing a file that can be inputed

Here is my code:
void commands(){
string CMDS = "CMDS";
cin >> CMDS;
if(CMDS == "CMDS"){
cout << "CLS- Clear command line" << endl;
cout << "Logout- Logs you out of the system" << endl;
cout << "TFile- Creates a text file" << endl;
commands();
}
else if(CMDS == "CLS"){
system("cls");
commands();
}
else if(CMDS == "Logout"){
cout << "Logging out" << endl;
system("cls");
Sleep(500);
mainTitle();
enterClass();
}
else if(CMDS == "TFile"){
system("cls");
std::string textf;
cout << "--Enter Your Text--" << endl;
ofstream file_;
file_.open("Text.txt");
std::getline(std::cin, textf);
file_ << textf << endl;
file_.close();
}
else{
cout << "Incorrect choice" << endl;
commands();
}
}
I need help getting it to work, because the std::getline just closes the program right after I try to write a text file. The program is suppose to let you input text that uses spaces and creates a text file.

Why is my file empty?

Why is my file 'database2' empty and no files being renamed? After the part where the problem is stated in comments, the file 'database2' becomes 0 bytes. The file 'database2' is also not renamed and the file 'database' is not being deleted. Please help me, here is part of my code:
int edit(){
char KeyStroke;
std::string strings;
string name;
string name1;
std::string dummy;
std::string strings2;
std::string strings3;
ifstream myfile;
ofstream myfile1;
bool found = false;
myfile.open("database");
cout << endl << "What is the name of the contact you wish to go in detail?" << endl;
getline(cin, name);
while ( !found && getline (myfile ,strings) ) {
if (strings.find(name) != std::string::npos) {
cout << endl << "Name:\t\t" << strings<<endl;
std::getline( myfile, strings );
cout << "Address:\t" << strings<<endl;
std::getline( myfile, strings );
cout << "Handphone:\t" << strings;
}
}
start:
cout << endl <<endl;
cout << "What do you wish to edit?"<<endl;
cout << "1) Name"<<endl;
cout << "2) Address"<<endl;
cout << "3) Handphone"<<endl;
cout << "4) Nothing" << endl;
myfile.close();
/*--Main part of this code is from here onwards--*/
lol:
myfile.open("database");
myfile1.open("database2");
KeyStroke = getch();
switch(KeyStroke){
case '1':
cout << "What is the new name: ";
getline(cin, name1);
while ( !myfile.eof()) {
getline (myfile ,strings);
if (strings.find(name) != std::string::npos) {
myfile1 << name1 << endl;
}
else{
if(strings[0] == ' '){
continue;
}
myfile1 << strings << endl;
}
}
myfile1 << " ";
myfile1.close(); /*Once the file closes here, the data written in earlier dissapears*/
myfile.close();
remove("database");
pause1();
rename("database2","database");
goto start;
This is whats happening:
You have a "loop" going on with the "start" label and the goto at the end. So this will be the first part of the loop:
cout << endl <<endl;
cout << "What do you wish to edit?"<<endl;
cout << "1) Name"<<endl;
cout << "2) Address"<<endl;
cout << "3) Handphone"<<endl;
cout << "4) Nothing" << endl;
myfile.close();
/*--Main part of this code is from here onwards--*/
lol:
myfile.open("database");
myfile1.open("database2");
cin.get (&KeyStroke,256);
See in the first part of your loop you open/create two files called "database" and "database2" (note that ofstream open method creates the file if it doesnt exist already) and then waits for the user input.
Lets say the user press 1 to change the name, at the end of the case 1 statement you have this:
myfile1 << " ";
myfile1.close(); /*Once the file closes here, the data written in earlier dissapears*/
myfile.close();
remove("database");
// pause1(); // undefined
rename("database2","database");
goto start;
You close the files, delete database, and rename databese2 to database, which is working as intended, and then you go back to the start of the "loop" with the goto, which excecutes this part of the code again:
cout << endl <<endl;
cout << "What do you wish to edit?"<<endl;
cout << "1) Name"<<endl;
cout << "2) Address"<<endl;
cout << "3) Handphone"<<endl;
cout << "4) Nothing" << endl;
myfile.close();
lol:
myfile.open("database");
myfile1.open("database2");
You open database file and since you renamed your old database2 to database (database2 now doesnt exist) it creates a new one (empty of course).
hope it helps.