【发布时间】:2018-02-17 00:54:00
【问题描述】:
我正在尝试编写从文件或标准输入中读取的代码,并导致文件或标准输入中的所有空白被“压缩”,这意味着只有最后一个空白字符序列打印空白。我的方法是创建一个映射,其中每个单词作为键,该单词后面的空格作为它的值。这可能有问题,因为我需要按插入顺序打印地图的内容,而且我也会有重复的键。我发现了 std::unordered_multimap 但我无法弄清楚我将如何实施它。
这是我所拥有的:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <iterator>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;
int main(int argc, char** argv) {
string filename;
char input;
map<string, string> words;
ostringstream os;
string word = "";
string spaces = "";
filename = argv[argc-1];
ifstream infile(filename);
while ( infile.get(input) ) {
os << input;
}
string filecontents = os.str();
for (int i = 0; i < filecontents.length(); ++i) {
if ( !isspace(filecontents[i])) {
if (spaces.length() >= 1) {
words[word] = spaces;
word = "";
spaces = "";
word += filecontents[i];
}
else {
word += filecontents[i];
}
}
else {
spaces += filecontents[i];
}
}
words[word] = "";
for (const auto& p : words) {
cout << p.first << p.second.back();
}
文件:
potato milk
sausage
输出:
milk
potato sausage
也许有更好的方法来做这件事?我应该补充一点,我是 C++ 的新手,嗯,一般来说是 C。任何帮助将不胜感激。
【问题讨论】:
-
如果命令行上没有指定参数——你是不是有点麻烦?
-
map、unordered_multimap和任何关联容器都不会保留插入顺序。只是一个std::vector<std::pair<std::string, std::string>>怎么样? -
也许您只需要自己存储这些单词,因为它们都有一个空格分隔它们?
std::vector<std::string> -
C 的新手或知识与 C++ 的关系不大。它们是不同的语言,尽管它们有一些共同的语法和特性,但用两种语言做某件事的最佳方式通常是完全不同的。
-
“我是 C++ 新手,嗯,一般来说是 C” 听起来你认为 C++ 是一种 C。它不是
标签: c++ string c++11 dictionary whitespace