微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符串和双精度的 C++ 重叠输出

如何解决字符串和双精度的 C++ 重叠输出

我一直在尝试解决 UVa10226,下面给出了我的错误代码

# include "bits/stdc++.h"
# include <cmath>
# include <algorithm>
# include <cstring>
# include <cstdio>

# define vi vector<int>
# define vvi vector<vi>
# define pi pair<int,int>
# define vii vector<pi>
# define rep(i,a,b) for(int i=a; i<b; i++)
# define ll long long int
# define fast ios_base::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);

using namespace std;

int main(int argv,char* argc[]){
    fast
    int n; string s;
    cin>>n;
    getline(cin,s);
    getline(cin,s);
    while(n--){
        map<string,int> mp;
        double total=0;
        while(!cin.eof()){
            getline(cin,s);
            if(s=="") break;
            auto it = mp.find(s);
            if(it==mp.end()) mp.insert({s,1});
            else (it->second)++;
            totaL++;
        }
        for(auto it=mp.begin(); it!=mp.end(); it++){ cout << it->first << " " << setprecision(4) << fixed << (it->second*100)/total << endl;}
        if(n!=0) cout << endl;
    }
}

这是控制台显示输出

 13.7931
 3.4483
 3.4483d
 3.4483
 3.4483alnut
 3.4483
 3.4483ood
 3.4483
 3.4483
 3.4483ry
 3.4483ple
 3.4483
 3.4483
 3.4483
 3.4483er
 3.4483
 6.8966
 3.4483as
 3.4483ple
 3.4483e
 10.3448k
Willow 3.4483
 3.4483Birch

当我在内部 while 循环中的 s[s.size()-1]=' ' 下方添加 getline() 时,输出得到更正。我不明白 getline() 在这里是如何工作的,以及为什么存在重叠。我认为最后一个字符是 '\n' 因为将输出发送到文本文件会在不同的行中打印出名称和编号。

我希望得到有关 getline() 如何在这里工作的帮助(我不明白为什么需要两个 getline()),以及为什么控制台中的输出很奇怪(我希望控制台中的输出是类似于在文本文件中获得的输出

(另外,“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

这是我一直在使用的输入文件

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。