English 中文(简体)
如何在++中使用线分
原标题:How to split using getline() in c++

我投入文件,

 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`

我正在使用线索(Mfile,line1[a], ~ );分成几条,我无法进一步分裂。 请允许我帮助我说一下。 感谢!

最佳回答

基本做法是首先使各栏具有更大的灵活性,减少硬编码。 与此类似:

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;

关于实际数据,请将first改为整个线,然后使用>。 a. 区分该行的内容:

    // 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    

如果你需要以不同顺序显示你的栏目,那么你可以首先将数值分为<条码>查询和设计;指示和编号;,然后按你想要的顺序计算。

问题回答

我正在使用<条码>植被线(Mfile,line1[a], ~ );,按<条码> ~进行分离,我无法就此进一步分裂。

The problem is not splitting the input lines. As was pointed out in the comments that is working fine.

问题是产出格式。 当你展示头衔时,你对每个领域使用不同的宽度。 此外,你在每一个外地名称之后添加了婚礼,这实际上导致职能<条码>tw<>>>>>/条码规定的宽度被忽略。

cout
    << left
    << setw(10)
    << "Stock Name              "   // Wider than 10
    << left
    << setw(5)
    << " Value  "                   // Wider than 5
    << left
    << setw(8)
    << "Quantity   "                // Wider than 8
    << left
    << setw(5)
    << "   Total Worth  "           // Wider than 5
    << endl;

之后,当你得出实地价值时,你使用单一宽度:

cout
    << left
    << setw(10);

It should not surprise you that the columns do not line up.

Read one record at a time

打上栏的最容易的方法是排除所有胎盘,并使用<代码>std:setw控制 w栏。

I recommend reading each line (i.e., record) into a string, and then using a stringstream to further parse it:

    std::string line;
    while (std::getline(myfile, line))    // Keep looping while you read a line successfully.
    {
        std::stringstream sst{ line };    // Load the line into a `stringstream`.
        // ...
    }

Use named fields

Using named fields makes it easier to keep track of the ones you want to output.

// If your course has covered `struct`, you can place 
// these fields within a `struct`.

std::string ticker_symbol;
std::string stock_name;
std::string value;
std::string quantity;
std::string percent_change;
std::string unknown_field1;
std::string total_worth;
std::string trade_date;
std::string unknown_field2;

Read each field separately

// Use an if-statement to verify that each of the fields 
// was successfully extracted from the `stringstream`.

if (std::getline(sst, ticker_symbol,  ~ ) &&
    std::getline(sst, stock_name,  ~ ) &&
    std::getline(sst, value,  ~ ) &&
    std::getline(sst, quantity,  ~ ) &&
    std::getline(sst, percent_change,  ~ ) &&
    std::getline(sst, unknown_field1,  ~ ) &&
    std::getline(sst, total_worth,  ~ ) &&
    std::getline(sst, trade_date,  ~ ) &&
    std::getline(sst, unknown_field2))  // no  ~  here.
{
    // Extraction successful. Output the fields you need, 
    // followed by `std::endl` (or  
 ). Use `std::setw` 
    // to set a separate width for each field.
}
else
{
    // Extraction failed. Output an error message.
}

You will need to fiddle with the widths to get the columns to line up.

由于这似乎属于某种家务劳动,我把细节留给你。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签