读取空的不良字符串C ++

时间:2015-09-17 13:49:02

标签: c++ dictionary getline

所以我使用map<string,int>将字符串与整数值相关联,这样每个int表示字符串出现的次数,最后我打印每个字符串的次数和百分比它出现了。

我的代码就是:

#include <bits/stdc++.h>

using namespace std;

typedef vector<int> vi;
typedef pair<int,int> ii;

typedef vector<string> mc;

typedef vector<ii> vii;


int main(int argc, char const *argv[])
{
    int T ;

    cin>>T;

    while(T--){
        string s;
        map<string,int> m;
        int to=0;
        getline(cin,s);
        while(getline(cin,s)){
            if(m[s]==0){
                m[s]=1; 
            }
            else 
                m[s]++;
            to++;
        }
        for (map<string,int>::iterator i = m.begin();i!=m.end();i++){
            cout<<i->first<<" ";
            printf("%0.4lf\n",(double)i->second/(double)(to-1) *100.0);
        }


    }



    return 0;
}

但出于同样的原因,输出是:

 3.4483
Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483

我的输入:

1

Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow

必须是:

Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483

我想我可能已经读过一条空行,但我无法弄清楚我是怎么做到的,有人可以告诉我,我做错了。

3 个答案:

答案 0 :(得分:4)

这是完全可以预期的。您的输入包含两个标题行,您只能跳过一个。最简单的解决方案是使用第二次调用getline()跳过此行。

顺便说一句,在您的问题中粘贴代码时请不要使用竞争性编码快捷方式。 (#include <bits/stdc++.h>和其他神秘的typedef)

答案 1 :(得分:2)

在您正在读取文件的while循环中,您需要测试该行是空的还是所有空格,如果是,则跳过它。

答案 2 :(得分:1)

只需检查string is empty