简体   繁体   English

使用iomanip格式化矢量输出

[英]formatting vector output using iomanip

I'm having some trouble here. 我在这里遇到麻烦。 I have a file that looks like this (here's a snippet) 我有一个看起来像这样的文件(这是一个片段)

Sophia F 22158
Emma F 20791
Isabella F 18931
Jacob M 18899
Mason M 18856
Ethan M 17547

and I want to put each name, and the name's respective number into seperate vectors. 我想将每个名称和名称的相应编号放入单独的向量中。 For example, I would have 4 vectors: 1 for women's names and 1 for women's numbers, and the same for men's and men's numbers. 例如,我将有4个向量:1个代表女性的名字,1个代表女性的数字,男人和男人的数字相同。 (so 4 total) (总共4个)

I have this code, which will go through the file and pull out these elements and put them in vectors. 我有这段代码,它将遍历文件并提取这些元素并将其放入向量中。

for (int i = 0; i < numTimes; i++) {
        getline (inputFile, inputLine);
        ss.str(inputLine); //ss is a string stream
        ss >> name >> gender >>  popularity;
        if (gender == 'M') {
            mNames[i] = name;
            mFrequency[i] = popularity;
        } else if (gender == 'F') {
            fNames[i] = name;
            fFrequency[i] = popularity;
        }

        ss.clear();

    }

and I use this method to print it out: 我使用这种方法将其打印出来:

cout << counter << " Most Popular Baby Names" << endl << endl;
    cout << left << setw(15) << "Girls" ;
    cout << right << setw(9) << "Frequency" <<"      ";
    cout << left << setw(15) << "Boys";
    cout << right << setw(9) << "Frequency" << endl;
    for (int i = 0; i < counter; i ++) {
        cout << left << setw(15) << fNames[i] ;
        cout << right << setw(9) << fFreq[i] <<"      ";
        cout << left << setw(15) << mNames[i];
        cout << right << setw(9) << mFreq[i] << endl;
   {

but then I get this output: http://i.stack.imgur.com/2x0ta.png 但随后我得到以下输出: http : //i.stack.imgur.com/2x0ta.png

But I would like for it to be like this: http://i.stack.imgur.com/OSIX9.png 但我希望它像这样: http : //i.stack.imgur.com/OSIX9.png

So I'm thinking I either need to go through before I print and remove all the whitespace/0's in these vectors, or I need to check while I'm printing out. 因此,我认为我要么需要在打印之前删除这些矢量中的所有空格/ 0,要么先进行检查,或者在打印时检查一下。 Does anyone have any pointers? 有人有指针吗?

Solved, thanks guys. 解决了,谢谢大家。

I used two separate while loops, one for each set of arrays. 我使用了两个单独的while循环,每个数组一组。 In between them I reset the ifstream back to the beginning. 在它们之间,我将ifstream重新设置为开始。 This way, it goes through until each vector has 5 non-zero elements. 这样,直到每个向量具有5个非零元素为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM