C ++从.txt文件逐行读取每行的行字符串和数字数据类型

时间:2017-09-21 19:55:09

标签: c++ fstream

所以我试图在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;
}

1 个答案:

答案 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;
}
相关问题