【发布时间】:2020-05-16 18:03:02
【问题描述】:
我在 C++ 编程语言中进行以下练习:
读取一系列可能以空格分隔的(名称,值)对, 其中名称是单个空格分隔的单词,值是 整数或浮点值。计算并打印总和 每个名称的平均值以及所有名称的总和和平均值。
例如,给定:
hello world5.678popcorn 8.123 rock 123 hello world 8.761 popcorn 98 rock 1.9rock2.3
我的实现的输出是:
rock: Sum (127.2), Mean (42.4)
hello world: Sum (14.439), Mean (7.2195)
popcorn: Sum (106.123), Mean (53.0615)
我的实现:
#include <iostream>
#include <string>
#include <unordered_map>
std::unordered_map<std::string, double> pairs;
std::unordered_map<std::string, int> occurences;
void save(const std::string& name, const std::string& value);
void trim(std::string& s, const std::string& chars = " ");
int main() {
std::string line;
getline(std::cin, line);
std::string name;
std::string value;
bool name_saved;
for(char c : line) {
if(!name_saved && isdigit(c)) { // reached end of name
name_saved = true;
trim(name);
value += c;
} else if(!name_saved) { // add char to name
name += c;
} else if(name_saved) {
if(isdigit(c) || (c == '.' && (value.find_first_of(".") == std::string::npos))) { // add char to value
value += c;
} else { // reached end of value
trim(value);
save(name, value);
name = "";
value = "";
name_saved = false;
if(isalpha(c)) {
name += c;
}
}
}
}
if(value != "") {
save(name, value);
}
std::cout << "\n";
for(auto pair : pairs) {
std::cout << pair.first << ": " << "Sum (" << pair.second << "), Mean (" << (pair.second / occurences[pair.first]) << ")\n";
}
return 0;
}
void save(const std::string& name, const std::string& value) {
pairs[name] += std::stod(value);
occurences[name]++;
}
void trim(std::string& s, const std::string& chars) {
s.erase(0, s.find_first_not_of(chars));
s.erase(s.find_last_not_of(chars) + 1);
}
我想知道这个练习更有效的方法是什么?我觉得我的代码很乱,我想就我可以用什么来清理它并使它更紧凑一些输入。
【问题讨论】:
-
你知道
std::istringstream怎么用吗? -
@SamVarshavchik 不,我没有。我会调查一下谢谢。
-
@SamVarshavchik:用于提取名称和值的```std::istringstream``` 将不起作用,因为名称和值之间有时没有空格。或者,我误解了你的想法,你的意思是不同的方法。