如何在c++中使用getline()进行分割

问题描述 投票:0回答:1

我的输入文件,

 AMZN~Amazon.Com Inc~1402.05~+24.10~+1.75%~4854900~6806813~01/26/18~1523
 AAPL~Apple Inc~171.51~+0.40~+0.23%~39128000~6710843~01/26/18~1224`

我的代码,

 #include <iostream>
 #include <fstream>
 #include <string>
 #include <iomanip>
 using namespace std;

 int main()
 {
    string line1[30];
    string line2[30];
    ifstream myfile("sp03HWstock.txt");
    int a = 0;

    if(!myfile) 
    {
    cout<<"Error opening output file"<<endl;
    system("pause");
    return -1;
    }
    cout
       << left
       << setw(10)
       << "Stock Name              "
       << left
       << setw(5)
       << " Value  "
       << left
       << setw(8)
       << "Quantity   "
       << left
       << setw(5)
       << "   Total Worth  "
       << endl;
  while(!myfile.eof())
  {
   getline(myfile,line1[a],'~');

    cout
        << left
        << setw(10);


   cout<<  line1[a];
  }
}

所需输出,

Stock Name               Value  Quantity      Total Worth  
Amazon.Com Inc          1402.05 +24.10        6806813   
Apple Inc               171.51  +0.23%        6710843

我得到的输出,

Stock Name               Value  Quantity      Total Worth  
AMZN     Amazon.Com Inc1402.05   +24.10    +1.75%    4854900   6806813   01/26/18  1523
AAPLApple Inc 171.51    +0.40     +0.23%    39128000  6710843   01/26/18  1224`

我正在使用 getline(myfile,line1[a],'~');用“~”分割,我无法对其执行进一步分割。有人可以帮我解决一下吗?谢谢!!

c++ arrays getline
1个回答
0
投票

一个基本方法是首先给自己更多的灵活性和更少的与列相关的硬编码。像这样的东西:

const int MAX_COLUMNS = 6;

struct {
    const char* name;
    int width;
} columns[MAX_COLUMNS] = {
    { "Stock", 6 },
    { "Name", 16 },
    { "Value", 10 },
    { "Quantity", 10 },
    { NULL },                 // Don't care
    { "Total Worth", 12 },
};

然后,您可以轻松输出列标题,如下所示:

    // Print column headings
    cout << left;
    for (int i = 0; i < MAX_COLUMNS; i++)
    {
        if (columns[i].name)
        {
            cout << setw(columns[i].width) << columns[i].name;
        }
    }
    cout << endl;

对于实际数据,您应该首先读取整行,然后使用

std::istringstream
来分割该行的内容:

    // Read and process lines
    string line;
    while (getline(myfile, line))
    {
        istringstream iss(line);
        string item;
        int count = 0;
        while (count < MAX_COLUMNS && getline(iss, item, '~'))
        {
            if (columns[count].name)
            {
                cout << setw(columns[count].width) << item;
            }
            ++count;
        }
        cout << endl;
    }

输出:

Stock Name            Value     Quantity  Total Worth 
AMZN  Amazon.Com Inc  1402.05   +24.10    4854900     
AAPL  Apple Inc       171.51    +0.40     39128000    

如果您需要以不同的顺序显示列,那么您可以首先将值拆分为

vector<string>
,然后以您想要的任何顺序输出。

© www.soinside.com 2019 - 2024. All rights reserved.