字符串和双精度的 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 (将#修改为@)