c++ - 读取空的不需要的字符串 C++

标签 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

我想我可能以某种方式读到了一个空行,但我不知道我是怎么做到的,请有人告诉我我做错了什么。

最佳答案

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

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

关于c++ - 读取空的不需要的字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32632000/

相关文章:

c++ - std::map 按值的大小排序 (set<int>)

c++ - 如何正确使用getline

c++ - 从字符串中获取行(不是从字符串流中获取)

c++ - 包装代码以避免重复的技术?

c++ - 检测多字节字符编码

python - 从 python 列表中获取字典

C - 尝试确定由 getline() 填充的缓冲区中的元素数

c++ - ostream 运算符重载

c++ - 如何使用某个驱动器中打开的文件夹关闭 Windows 资源管理器窗口

python - 在python中从字典中设置属性