C++文件包含多行
C++ file io multiple lines
我正在尝试一次一行地从.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();
}
相关文章:
- AcquireCredentialsHandleA() 返回 PFX 文件的0x8009030e(安全包中没有可用的凭据
- 禁止显示有关包含文件中 #pragma 包的警告
- 选择特定版本的 Visual Studio 命令行工具包,并根据特定版本的C++运行时环境编译文件
- 如何使用 AWS C++ 开发工具包在给定的开始和结束日期范围内列出 S3 中的文件
- 如何链接我自己的 .so 文件而不是操作系统捆绑包 .so 文件?
- 使用开发工具包将文件上传到 AWS C++
- TCP-Server以数据包结构(非Java客户端)发送文件
- 致命错误 C1083:无法打开包含文件:'atlbase.h' Pyinsane 包
- 可视化 将 TCP 服务器数据包保存到 C++ 中的文件
- Buildroot 包需要一个带有C++大文件错误的工具链
- 获取包含C++的捆绑包中文件的路径(CFBundleGetMainBundle)
- 数据包大小(每数据包 mBytes)或核心音频中 AAC 文件的比特率
- CMake 包配置文件中的泛型"transitive behavior" (find_dependency)
- Visual Studio 14.0 和 Windows 工具包中的错误包括文件夹
- 获取 PCAP 文件中数据包的 IP 地址
- 如何在 C++ 中读取 PCAP 文件以获取数据包信息
- 如何在C++中分析来自流量转储文件的数据包信息
- 拆包/解密/提取/application.bin文件
- Python:将二进制文件读取到一个结构中,然后拆包
- 如何在visual studio 2010 C++中制作带有所需.dll和lib(opencv)文件的.exe文件包