.CSV 文件的输出问题

Output issue with .CSV file

每当我尝试输出一行时,它会垂直输出文件中的数据,而不是水平输出整行。我的主要目标是单独输出每一行并删除逗号并重复直到 CSV 文件中没有更多行。

我运行代码时的一个例子:

cout << data[1] << "\t";

输出:

Huggenkizz      Pinzz   White   Dwarf   Dildock Operknockity    DeVille

我想得到的是:

Huggenkizz Amanda 3/18/1997 Sales Associate 2 A A F

我的 CSV 文件:

ID,Last Name,First Name,DOB,DtHire,Title,Level,Region,Status,Gender
1,Huggenkizz,Amanda,3/18/1997,,Sales Associate,2,A,A,F
2,Pinzz,Bobby,5/12/1986,,Sales Associate,3,B,A,F
3,White,Snow,12/23/1995,,Sales Associate,2,C,A,F
4,Dwarf,Grumpy,9/8/1977,,Sales Associate,2,C,A,M
5,Dildock,Dopey,4/1/1992,,Sales Associate,1,B,A,M
6,Operknockity,Michael,10/2/1989,,Sales Associate,1,A,S,M
9,DeVille,Cruella,8/23/1960,,Sales Manager,,,A,F

我的代码:

vector<string> SplitString(string s, string delimiter)
{
    string section;
    size_t pos = 0;
    vector<string> annualSalesReport;
    while ((pos = s.find(delimiter)) != string::npos) //finds string till, if not returns String::npos
    {
    section = (s.substr(0, pos)); // returns the substring section
    annualSalesReport.push_back(section); // places comma split section into the next array
    s.erase(0, pos + delimiter.length()); // removes the previous string up to the current pos
    }
    annualSalesReport.push_back((s));
 return annualSalesReport;
}
int main() 
{
    vector<string> data;
    string readLine;
    ifstream myIFS;
    myIFS.open("SalesAssociateAnnualReport.csv");
    int lineCounter = 0;
        while (getline(myIFS, readLine))
        {
            lineCounter++;
            if (lineCounter > 1)
            {
                data = SplitString(readLine, ",");
                if (data.size() > 1) //removes top line
                {
                    cout << data[1]<< "\t";
                }
            }
        }
        myIFS.close();
    

    return 0;
}

请按如下方式更改您的 main 函数

int main() 
{
    vector<vector<string>> data;
    string readLine;
    ifstream myIFS;
    myIFS.open("SalesAssociateAnnualReport.csv");
    int lineCounter = 0;
    while (getline(myIFS, readLine))
    {
        lineCounter++;
        if (lineCounter > 1)
        {
            vector<string> dataLine = SplitString(readLine, ",");
            data.push_back(dataLine);
        }
    }
    myIFS.close();
    // output the first data line of csv file without delimiter and without first column
    for (size_t i = 1; i < data[0].size(); i++)
    {
        cout << data[0][i] << '\t';
    }
    return 0;
}

获得你想要的

输出
Huggenkizz      Amanda  3/18/1997               Sales Associate 2       A      AF

无需更改您的 SplitString 功能。

请注意 C++ 第一个数组索引总是 0 而不是 1

我将 CSV 文件输入处理和输出生成分开,只是为了遵循简单的编程模型IPO:

Input -> Process -> Output

因此我引入了字符串矩阵 vector<vector<string>> 来存储整个所需的 CSV 文件数据。

如评论中所述,SplitString 函数可能会被重构,它也应该被修复以正确拆分最后两列。

希望对您有所帮助?