[英]C++ file io multiple lines
我正在嘗試一次從.txt文件讀取一行。 我想從每一行中獲取一個字符串和一個雙精度值。 每行都有一個名稱和薪水,用逗號分隔,例如
約翰·道爾(John Doyle),30000
伊恩·史密斯(Ian Smith),32000
等等
然后,我將更改這些值,然后將新值重新輸入到新的.txt文件中,例如
約翰·道爾,1100,31000,2300
伊恩·斯米特(Ian Smite),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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.