I want to find a specific id from file and modify content.
Here is originol code which I want.
// test.txt
id_1
arfan
haider
id_2
saleem
haider
id_3
someone
otherone
C++ Code:
#include <iostream>
#include <fstream>
#include <string>
using namesapce std;
int main(){
istream readFile("test.txt");
string readout;
string search;
string Fname;
string Lname;
cout<<"Enter id which you want Modify";
cin>>search;
while(getline(readFile,readout)){
if(readout == search){
/*
id remain same (does not change)
But First name and Last name replace with
user Fname and Lname
*/
cout<<"Enter new First name";
cin>>Fname;
cout<<"Enter Last name";
cin>>Lname;
}
}
}
Suppose:
A user search id *id_2*. After that user enter First name and Last name Shafiq and Ahmed.
After runing this code the test.txt File must modify the record like that:
...............
...............
id_2
Shafiq
Ahmad
.................
.................
Only id_2 record change remaing file will be same.
UPDATE:
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
}else{
outFile<<readLine<<endl;
}
}
}
It also contain pervious First Name and Last Name in temp.txt file.
After finding the specific id and writing the new first name and last name, you need to skip the following two lines. This code works:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void skipLines(ifstream& stream, int nLines)
{
string dummyLine;
for(int i = 0; i < nLines; ++i)
getline(stream, dummyLine);
}
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
skipLines(readFile, 2);
}
else
{
outFile<<readLine<<endl;
}
}
}
Related
So, I am trying to implement a function that can read a file and save some variables to it. The text file will look like this
- Account Number: 12345678
- Current Balance: $875.00
- Game Played: 2
- Total Amount Won: $125.00
- Total Amount Loss: $250.00
So far, I am able to read the account number but when I try to read the rest using the same method, nothing gets outputted to the console.
Here is my progress so far.
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
// Open the file
inFile.open(accID);
// Check if the account number exists
if (!inFile)
{
cout << "Account number does not exist.\n";
}
int num;
string str, str2, str3;
// Read through the file
while (inFile >> str >> str2 >> str3 >> num)
{
cout << num << " ";
}
return 0;
}
When I run this code, I can get the account number to be output, but when I try adding more variables to read through the rest of the file nothing gets output to console.
You can use std::getline to read the rest of the file as shown below:
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
std::cout<<accID<<std::endl;
// Open the file
ifstream inFile(accID);
if(inFile)
{
std::string strDash,strTitle, strNumber;
int num;
// Read through the file
while (std::getline(inFile, strDash, ' '),//read the symbol -
std::getline(inFile, strTitle, ':'), //read the title(for eg, Account number,Current Balance etc)
std::getline(inFile, strNumber, '\n')) //read the number at the end as string
{
std::cout<<strDash<<" "<<strTitle<<strNumber<<std::endl;//print everything read
}
}
// Check if the account number exists
else
{
cout << "Account number does not exist.\n";
}
return 0;
}
The output of the program can be seen here.
The code below,works fine but it does not take any value for age and terminates.`
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
/*Output
Enter your name:Jack
Enter your age:
C:\Users\user\documents\c++
*/
In the output section ,age is not accepted and the program terminates.
Use string name instead of char name[20] to take multi-character value. char name[20] will terminate after taking a single character.
Also, its valued will not be displayed on giving output.
Modified code for reference.
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
string name,server;
public:
void get(){
cout<<"Enter your name:";
cin>>name;
cout<<"Enter your age:";
cin>>age;
}
//test output
void put(){
cout<<name<<endl;
cout<<age<<endl;
}
};
int main(){
user u;
u.get();
//test
u.put();
return 0;
}
Just modify the code to this :
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name; // changes done here
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
Job Done :)
Your problem is here:
cin>>name[20];
Why:
'name[20]' is 21th char of the array you defined before. It counts from 0! As this, it is simply a single char. If you now enter more than a single char, the rest is read by the cin>>age.
Example:
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
std::cout << "Name " << name << std::endl;
std::cout << "Age " << age << std::endl;
And entering:
Enter your name:1234
Enter your age:Name
Age 234
As you see, the '1' is now in the name and the rest is stored in age.
But attention: You defined your array as `name[20], which means you have 0..19 elements. Accessing name[20] is wrong!
But what you simply want to do was:
cin >> name;
The easiest way to handle strings (a long sequence of characters) or even the strings that have spaces just use the following library in C++.
#include <bits/stdc++.h>
Then just declare a string variable.
String name;
Now you can save a very long string without any error. e.g.
name = jshkad skshdur kslsjue djsdf2341;
and you'll get no error, enjoy ;)
I want to separate a full name from each other. It only works for first name.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string FullName;
int i = 0;
cout <<"Enter your full name "<<endl;
getline(cin,FullName);
while (FullName[i] != ' ')
{
cout<<FullName.substr(i,FullName.find(' '))<<endl;;
i++;
}
cout <<endl;
}
return 0
}
I want to separate each name in a separate line like this: If I enter this:
Max Michael Max
the output should be with each name in a separate new line:
Max
Michael
Max
How can I split names each one in separate line ?
The simplest approach is to use std::istringstream after the name is read in.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string FullName;
cout <<"Enter your full name "<<endl;
getline(cin, FullName);
string namepart;
istringstream strm(FullName);
while ( strm >> namepart )
cout << namepart << '\n';
}
Live Example
In the code below I am trying to have the variable fullName be populated with whatever I enter during the operation of the function namecheck. I am not sure where I am going wrong. Please help and thank you for it.
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
string namecheck();
int main()
{
cout<<fixed;
string firstName;
string lastName;
string fullName;
char action;
int pin;
int pinTry =1;
int actionsTaken =0;
int joeyPin = 4433;
int mildredPin = 2849;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
double withdraw;
double deposit;
namecheck();
cout<<fullName;
}
string namecheck(){
string firstName;
string lastName;
string fullName;
string completeName;
double joeyTotal = 3742.55;
double mildredTotal = 19.36;
cout<<"Welcome to Blah National Bank!\n";
cout<<"What is your first name?\n";
cin>>firstName;
if (firstName == "END"){
cout<<"User totals: \n"
<<"Joey Stowy:\t"<<setprecision(2)<<joeyTotal<<endl<<endl
<<"Mildred Moredebt:\t"<<setprecision(2)<<mildredTotal<<endl<<endl;
}
if (firstName != "END"){
cout<<"What is your last name?\n";
cin>>lastName;
}
fullName = firstName+" "+lastName;
return fullName;
}
Change:
namecheck();
cout<<fullName;
to:
fullname = namecheck();
cout<<fullName()
.
When you call namecheck() in main, assign the result to fullName:
fullName = namecheck();
I'm working on a project of splicing an inputted string of a name, and for some reason it's not working. Part of it is code copied from my book that supposedly works, so I'm stuck. Am I doing something wrong?
#include <iostream>
#include <string>
using namespace std;
void main()
{
string name;
int index;
cout<<"Please enter your full name. ";
cin>>name;
cout<<"\n"<<endl;
index = name.find(' ');
cout<<"First Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
index = name.find(' ');
cout<<"Middle Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
cout<<"Last Name: "<<name<<" "<<name.length()<<endl;
}
Most peoples' names consist of at least two words. This will only get one of them:
cout<<"Please enter your full name. ";
cin>>name;
istream operator>> is whitespace delimited. Use getline instead:
std::getline(std::cin, name);
For your purposes, you could probably do this, which is simpler:
std::string first, middle, last;
std::cin >> first >> middle >> last;