所以我试图在c ++程序中读取.txt文件。文本文件中的每一行都有firstName,lastName和annualSalary(例如,Tomm Dally,120000)。 我似乎可以正确读取文件 - 它跳过第一列(firstName)并在第一行后停止读取数据。那是为什么?
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
double backPayDue;
double newAnualSalary;
double newMonthlyWage;
int numOfEmployees = 0;
double totalBackPayDue = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (!empSalariesOld.fail())
{
while (empSalariesOld >> fName)
{
empSalariesOld >> fName >> lName >> yearlyPay;
std::cout << fName << " " << lName << " " << yearlyPay << endl;
numOfEmployees++;
}
}
empSalariesOld.close();
empSalariesNew.close();
system("pause");
return 0;
}
答案 0 :(得分:0)
当您的while
语句首次调用empSalariesOld >> fName
时,它会读取员工的名字。然后,在循环体内,当您致电empSalariesOld >> fName >> lName >> yearlyPay
时,>> fName
会读取员工的姓氏(因为您已经读过第一个 >姓名),然后>> lName
读取员工的薪水,>> yearlyPay
尝试阅读下一位员工的名字并且失败了!
尝试更类似于以下内容的内容。使用std::getline()
读取整行,然后使用std::istringstream
解析它:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (iss >> fName >> lName >> yearlyPay) {
std::cout << fName << " " << lName << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}
但是,如果这些行实际上在您显示的名称和工资之间有一个逗号(Tomm Dally, 120000
),那么请尝试以下代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string name;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (getline(iss, name, ',') && (iss >> yearlyPay))
std::cout << name << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}