C++ 读取空字符串C++;

C++ 读取空字符串C++;,c++,dictionary,getline,C++,Dictionary,Getline,因此,我使用map将一个字符串与一个整数值相关联,这样每个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

因此,我使用
map
将一个字符串与一个整数值相关联,这样每个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;
}
我的意见是:

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

我想我可能读到了一个空行,但我不知道我是怎么做的,有人可以告诉我我做错了什么。只需检查文件中正在读取的while循环中的。

是否需要测试该行是否为空或全部为空白,如果是,则跳过它。

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

顺便说一下,在问题中粘贴代码时,请不要使用竞争性编码快捷方式。(
#包括
和其他神秘的typedef)

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