用C++重写一个文本文件
问题描述:
使用一个处理文件流的程序。我想编辑存储在文本文件中的一行文本。根据我的理解,最好的方法是从原始文件中复制所有内容并将其覆盖在一个新文件中,并在编辑过程中进行编辑。我一直无法在网上找到一个清晰的例子,并想知道我能否看到一个例子。用C++重写一个文本文件
例如文本文件包含:
user1 pass1 55
user2 pass2 56
user3 pass3 57
我想编辑对地方有:
user1 pass1 55
user2 pass2 44
user3 pass3 57
这里是我的情况下删节代码:
#include <iostream>
#include <fstream>
using namespace std;
//function prototypes
void addUser();
void part1();
int main();
//global variables
string username;
string password;
int balance;
void addUser(){
//open a file in write mode
ofstream myfile;
myfile.open("userinfo.txt", ios::app);//append the text file
if(myfile.is_open()){
cout<<"Please Create a Username: ";
string inputCheck;//a string to compare name
cin>>inputCheck;
cout<<"Please Create a Password: ";
cin>>password;
cout<<"Current Balance: ";
cin>>balance;
myfile<<inputCheck<<' '<<password<<' '<<balance<<"\n";
myfile.close();
cout<<"User account '"<<inputCheck<<"' has been created"<<endl;
}//ends create a password else
part1();
}
void part1()
{
cout<<"1.Add User\n2.Edit Information"<<endl;
int input;
cin>>input;
if(input == 1){
addUser();
}else if(input == 2){
//find the user
cout<<"Enter the username: ";
string checkUser;
cin>>checkUser;
ifstream infile("userinfo.txt"); //CREATING IFSTREAM
ofstream outfile("pleasework.txt");
bool foundUser = false;
while(infile>>username>>password>>balance){
if(checkUser==username){
foundUser = true;
break;
}
}
if(foundUser){
cout<<"Current Balance: "<<balance<<endl;
cout<<"Enter new balance: ";
int newBalance;
cin>>newBalance;
if(infile.is_open()){
outfile<<username<<' '<<password<<' '<<newBalance<<endl;
//How do I get all of the other unedited accounts in here?!?!?!?!
}
}//end input 2
infile.close();
outfile.close();
}
}//end part 1
int main(){
part1();
}
答
下面是一些伪代码,这可能有助于:
方法1:
open existing file in 'read' mode
open new file in 'write' mode
for each line in existing:
if line doesn't need update:
write line to new file
else:
make changes to values from line
write updated line to new file
close existing file
close new file
move new file over existing file
方法2:
open existing file in 'read/write' mode
data = array of lines
for each line in existing:
read values into data
clear existing file
add/delete rows in data if necessary
for each row in data:
update values in row
write updated line to existing file
close existing file
,一定不要调用主。 http://*.com/questions/2128321/can-main-function-call-itself-in-c – drescherjm
为什么你声明主?它已经被声明和超载。这个灾难就是如果你在你的函数中调用main函数,并且通常从main函数调用该函数是一个像无限循环或无限递归的无尽调用 – Raindrop7
@ Raindrop7了解。我将在稍后介绍其他功能。目前,该计划正在运行,正在做我需要的事情。感谢你为什么称主要是一件坏事,并可能导致灾难和无限循环的事情信息 – cparks10