C++文件包含多行

C++ file io multiple lines

本文关键字:文件包 C++      更新时间:2023-10-16

我正在尝试一次一行地从.txt文件中读取。 我想从每行中获取一个字符串和一个双精度值。每行都有一个名字和一个薪水,用逗号分隔,例如

约翰·道尔,30000

伊恩·史密斯, 32000

等。

然后,我将更改这些值并将新值重新输入到新的.txt文件中,例如

约翰·道尔, 1100, 31000, 2300

伊恩·斯密特, 1300, 32000, 3000

我真的不确定我是否走对了路。我当前的代码:

#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
double data;
ifstream infile;
infile.open("worker.txt");
ofstream outfile;
outfile.open("worker2.txt");
infile >> name >> data;
while (!infile.fail())
{
//do something with the name and salary read in
double backPay = data * 7.6 / 100 / 2;
double newAnnual = data * 7.6 / 100 + data;
double newMonthly = data * 7.6 / 100 + data;
double monthly = newMonthly / 12;
// write inputted data into the file.
outfile << backPay << ", " << newAnnual << ", " << monthly << ", " << 
endl;
// then try another read
infile >> name >> data;
}
outfile.close();
infile.close();
}

这是您要求的工作版本。

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string name;
string tempData; //since getline function only accepts string params, you need this
double data;
ifstream infile;
infile.open("worker.txt");
ofstream outfile;
outfile.open("worker2.txt");
while (getline(infile, name, ',')) //firstly get the name as Johnny suggested
{
getline(infile, tempData); // while on the same line, we can read the salary of that person
data = atof(tempData.c_str()); //now convert the gotten string value into a double for calculations
double backPay = data * 7.6 / 100 / 2;
double newAnnual = data * 7.6 / 100 + data;
double newMonthly = data * 7.6 / 100 + data;
double monthly = newMonthly / 12;
// write inputted data into the file.
outfile << name << ", " << backPay << ", " << newAnnual << ", " << monthly << endl; //write the name and values as required into the output file  
}
outfile.close();
infile.close();
}