I have been trying to solve UVa10226, and my buggy code is given below.
# 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;
}
}
Here is the output which the console shows:
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
The output is corrected when I add s[s.size()-1]=' '
below the getline()
in the inner while loop. I don't understand how getline()
works here, and why there is overlap present. I think the last character is '\n' because sending the output to a text file prints out the name and number in different lines.
I would appreciate help regarding how getline() is working here (I don't understand why the two getline()
are needed), and why the output in the console is weird (I expected the output in console to be similar to the output obtained in a text file)
(Also, the reason "Willow" appears properly is because it is the last line of the input file)
The output of the textfile:
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
Here's the input file which I've been using:
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