Remove specific line from file C++ - c++

I've been struggling all day with this problem. I can't make my program to delete an specific line of my file. I have a list of names in my file and I would like to delete one of them, I don't know what I'm missing.
EDIT: Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
string fname;
string keyword;
int phone_num;
ifstream myfile;
ofstream phone;
void Add()
{
ofstream phone("number.txt", ios::app);
cout << "Enter Name: ";
cin >> fname;
cout << "Enter Phone Number: ";
cin >> phone_num;
if (phone.is_open())
{
phone << fname << endl;
phone << phone_num << endl;
cout << "Contact saved successfully!" << endl;
}
phone.close();
}
void All()
{
ifstream myfile("number.txt", ios::in);
while(myfile >> fname >> phone_num)
{
for(auto name : fname)
{
cout << name;
}
cout << endl;
}
}
void Delete()
{
ifstream myfile("number.txt", ios::in);
cout << "Enter Name to delete : ";
cin >> keyword;
while(getline(myfile, keyword))
{
fname.replace(fname.find(keyword),keyword.length(),"");
}
}

Related

How to create multiple file in fstream with loop [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 2 years ago.
I am new in coding and in this community I want to save multiple student info in multiple file in ".txt" file like "student1.txt", "student2.txt", "student3.txt" etc. See my code then I hope you will understand my problem.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
for(int i = 1; i < 30; i++) {
string name, roll, gpa;
cout << "Enter student info";
cout << "name :";
cin >> name;
cout << "\nEnter Roll :";
cin >> roll;
cout << "\nEnter gpa :";
cin >> gpa;
ofstream file;
/* Problem part :I know this part of code will never work */
file.open("Student <<i<<".txt");
/* what should I do */
file << name << endl << roll << endl << gpa;
file.close();
}
}
Here is what I think you need: std::to_string and operator+ (string)
Check out the answers on this thread. There they have shown numerous methods to do this.
Code:
#include <fstream>
#include <iostream>
#include <string>
int main() {
for (int i = 1; i < 30; i++) {
std::string name, roll, gpa;
std::cout << "Enter student info : " << std::endl;
std::cout << "Name : ";
std::cin >> name;
std::cout << "Enter roll number : ";
std::cin >> roll;
std::cout << "Enter GPA : ";
std::cin >> gpa;
std::ofstream file("Student" + std::to_string(i) + ".txt");
file << name << std::endl
<< roll << std::endl
<< gpa << std::endl;
}
}

Incorrectly returning a value from a function in C++

>
Code:
int main ()
{
ifstream inStream;
ofstream outStream;
getInputOutputStreams(inStream, outStream);
numberFile(inStream, outStream);
return EXIT_SUCCESS;
}
I have been stuck with an issue where the code I wrote compiles, but when running it has to be terminated because it just lags. I believe my issue may have to deal with not correctly returning the names of the input and output files, but I cannot figure out where I'm going wrong. I'm only a beginner in C++ (we are just now learning about arrays), so if you think this is a dumb question I'm sorry!
Here is the code I have written:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
string getInputOutputStreams(ifstream &inStream, ofstream &outStream);
void numberFile(ifstream &inStream, ofstream &outStream);
int main ()
{
ifstream inStream;
ofstream outStream;
getInputOutputStreams(inStream, outStream);
numberFile(inStream, outStream);
return EXIT_SUCCESS;
}
string getInputOutputStreams(ifstream &inStream, ofstream &outStream)
{
string inputFile;
string outputFile;
cout << "Enter the name of the input file:" << endl;
cin >> inputFile;
inStream.open(inputFile);
while (inStream.fail()) {
cout << "Invalid file name." << endl;
cout << "Enter the name of an input file:" << endl;
cin >> inputFile;
inStream.open(inputFile);
}
inStream.close();
cout << "Enter the name of the output file:" << endl;
cin >> outputFile;
outStream.open(outputFile);
while (outStream.fail()) {
cout << "Invalid file name." << endl;
cout << "Enter the name of an output file:" << endl;
cin >> outputFile;
outStream.open(outputFile);
}
outStream.close();
return inputFile;
return outputFile;
}
void numberFile(ifstream &inStream, ofstream &outStream)
{
string inputFile;
string outputFile;
inStream.open(inputFile);
outStream.open(outputFile);
int lineNumber = 0;
string line;
while(!inStream.eof()) {
if(line == " ") {
}
else {
lineNumber++;
outStream << lineNumber << ": " << line << endl;
}
getline(inStream, line);
}
cout << lineNumber << " lines processed" << endl;
inStream.close();
outStream.close();
}
I see a number of mistakes:
getInputOutputStreams() is closing the streams that it opens.
incorrect return statements in getInputOutputStreams().
numberFile() is re-opening the streams, using filename strings that have no values.
using while(!inStream.eof()) is bad.
not ignoring blank lines, as the instructions ask for.
Try this instead
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void getInputOutputStreams(ifstream &inStream, ofstream &outStream);
void numberFile(ifstream &inStream, ofstream &outStream);
int main ()
{
ifstream inStream;
ofstream outStream;
getInputOutputStreams(inStream, outStream);
numberFile(inStream, outStream);
return EXIT_SUCCESS;
}
void getInputOutputStreams(ifstream &inStream, ofstream &outStream)
{
string inputFile;
string outputFile;
cout << "Enter the name of the input file:" << endl;
cin >> inputFile;
inStream.open(inputFile);
while (inStream.fail()) {
cout << "Invalid file name." << endl;
cout << "Enter the name of an input file:" << endl;
cin >> inputFile;
inStream.open(inputFile);
}
cout << "Enter the name of the output file:" << endl;
cin >> outputFile;
outStream.open(outputFile);
while (outStream.fail()) {
cout << "Invalid file name." << endl;
cout << "Enter the name of an output file:" << endl;
cin >> outputFile;
outStream.open(outputFile);
}
}
void numberFile(ifstream &inStream, ofstream &outStream)
{
int lineNumber = 0;
string line;
while (getline(inStream, line)) {
if (line != "") {
++lineNumber;
outStream << lineNumber << ": " << line << endl;
}
}
cout << lineNumber << " lines processed" << endl;
}

Phone number lookup within text file

Basically My Program Goal is that i have a file containing 4 telephone numbers
it would Look Like this
Harry Keeling (555)123-4567
Frank James (555)123-8901
Arthur Paul (555)987-4567
Todd Shurn (555)987-8901
What my program is doing right now is prompting the user for the name and last name and iterates through the file to see if their is a match if their is a match the phone number is saved in the variable phone number if their isnt a match the program outputs error right now my program is doing what is susposed to do but after each match is found the program is susposed to prompt do you want to continue looking up numbers y or n if it is a yes it is susposed to loop through the file again but basically my program isnt working and i have no idea why my code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&); // prototype
int main()
{
ifstream myfile;
string phonenumber;
string choice;
lookup_name(myfile, phonenumber);
if (phonenumber == " ") {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is" << phonenumber << endl;
cout << "Do you Want to look up another name in the directory?" << " " << "<Y/N" << endl;
cin >> choice;
if (choice == "Y")
lookup_name(myfile, phonenumber);
}
}
void lookup_name(ifstream& myfile, string& phonenumber)
{
string fname;
string lname;
string name1, name2, dummy, choice;
myfile.open("infile.txt");
cout << "What is your first name" << endl;
cin >> fname;
cout << "What is your last name" << endl;
cin >> lname;
for (int i = 0; i < 4; i++) {
myfile >> name1 >> name2;
if (fname + lname == name1 + name2) {
myfile >> phonenumber;
myfile.close();
if (choice == "Y")
{
continue;
}
else {
myfile >> dummy;
}
}
}
}
You need to add a loop inside of main() itself to prompt the user to continue, and you need to fix the mistakes in your lookup_name() function.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <limits>
using namespace std;
bool lookup_name(istream&, const string&, string&); // prototype
int main()
{
ifstream myfile("infile.txt");
string name, phonenumber, choice;
do
{
cout << "What is the name? ";
getline(cin, name);
if (!lookup_name(myfile, name, phonenumber)) {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is '" << phonenumber << "'" << endl;
}
cout << "Do you want to look up another name in the directory (Y/N)? ";
cin >> choice;
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
if ((choice != "Y") && (choice != "y"))
break;
myfile.seekg(0);
}
while (true);
return 0;
}
bool lookup_name(istream& myfile, const string& name, string& phonenumber)
{
string line, fname, lname;
while (getline(myfile, line))
{
istringstream iss(line);
if (iss >> fname1 >> lname)
{
if (name == (fname + " " + lname))
return getline(iss, phonenumber);
}
}
return false;
}

Ifstream code is not placing the input into the variable

Here's my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//variable init
ifstream inFile;
ofstream outFile;
string toPrint, fileName;
string var;
cout << "Enter your save file: "; cin >> fileName;//asks the file name
cout << "Searching..."<<endl;
string fileLocation = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";//locates it
inFile.open(fileLocation.c_str());
if(!inFile){//checks if the file is existent
cerr << "Error can't find file." << endl;
outFile.open(fileLocation.c_str());
outFile << "Player House: Kubo"<<endl;
outFile.close();
}
cout << "Loaded." << endl;
inFile.ignore(1000, ':'); inFile >> var; //gets the string and places it in variable named var
cout << var<<endl;
//replaces var
cout << "Enter a string: ";
cin >> var;
//saving
outFile.open(fileLocation.c_str());
outFile << "Player House: " << var;
inFile.close();
outFile.close();
}
Problem here is that I can't get the player's house named "Kubo" and place it in variable named "var". It manages to create the file in my documents and manages to change the variable in the replaces var section.
From what I understood, you need to simultaneously read and write a file. Try this code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string fileName;
cout << "Enter your save file: ";
cin >> fileName;
string filePath = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";
fstream file(filePath, fstream::in | fstream::out | fstream::trunc); // open modes to read and write simultaneously
string var;
if (file.tellg() == 0)
file << "Player House: Kubo\n";
file.seekg(14);
file >> var;
cout << var << endl;
file.close();
return 0;
}
I used tellg() to determine whether file is empty, you could also go with
file.peek() == ifstream::traits_type::eof();

Over looping (Cout) in C++

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
char hold;
string name;
char num1;
char num2;
int main() {
cout << "Hello!\n";
cout << "Tell me your name?: ";
cin >> name;
cout << "Well well well, if it isn't "<< name << "!\n";
cout << "Enter a NUMBER " << name << ": ";
cin >> num1;
while(!isdigit(num1)) {
cout << "Enter a NUMBER " << name << ": ";
cin >> num1;
}
cin >> hold;
system("pause");
return 0;
}
The problem is, it is overlooping the cout. How do I fix it?
Thanks.
A better way is to use std::stringstream (note: include sstream)
int getNumber()
{
std::string line;
int i;
while (std::getline(std::cin, line))
{
std::stringstream ss(line);
if (ss >> i)
{
if (ss.eof())
{
break;
}
}
std::cout << "Please re-enter your input as a number" << std::endl;
}
return i;
}
This replaces your while loop, and you make the call after asking for a number as you already figured out how to do.
The following is a shortened version of the original attempt. However, as with the original, it only checks a single character.
If I changed num1 to be an int then i'd need to check whether the input was valid as #Dieter Lucking mentioned.
#include <iostream>
using namespace std;
int main() {
char num1;
do {
cout << "\nEnter a number: ";
cin >> num1
} while(!isdigit(num1));
}
A bit of a variation on staticx's solution, which will pass Dieter Lücking's echo "" | test line.
I use an istringstream and get input until no more standard input or I get valid input. I pushed it all into a templated Get function that can be used for any type; you just need to give it a prompt for the user:
Get() function
template<typename T>
void Get(T& toSet, std::string prompt) // read from cin
{
std::string nextIn;
cout << prompt;
getline(cin >> std::ws, nextIn);
istringstream inStream(nextIn);
while(cin && !(inStream >> toSet))
{
inStream.clear();
cout << "Invalid Input. Try again.\n" << prompt;
getline(cin >> std::ws, nextIn);
inStream.str(nextIn);
}
if (!cin)
{
cerr << "Failed to get proper input. Exiting";
exit(1);
}
}
And you'd use it like so:
int myNumber = 0;
Get(myNumber, "Please input a number:");
Full code:
Live Demo
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template<typename T>
void Get(T& toSet, std::string prompt) // read from cin
{
std::string nextIn;
cout << prompt;
getline(cin >> std::ws, nextIn);
istringstream inStream(nextIn);
while(cin && !(inStream >> toSet))
{
inStream.clear();
cout << "Invalid Input. Try again.\n" << prompt;
getline(cin >> std::ws, nextIn);
inStream.str(nextIn);
}
if (!cin)
{
cerr << "\nFailed to get proper input. Exiting\n";
exit(1);
}
}
int main()
{
string name;
int num1 = -1;
cout << "\nHello!\n";
Get(name, "\nTell me your name?:");
cout << "\nWell well well, if it isn't "<< name << "!\n";
Get(num1, std::string("\nEnter a NUMBER, ") + name + ": ");
cout << "\nYou entered number: " << num1 << std::endl;
return 0;
}