C++ 你能阻止istream或stringstream吞并新行吗?

C++ 你能阻止istream或stringstream吞并新行吗?,c++,stl,C++,Stl,对于我的家庭作业项目,我必须阅读一本书,然后逐字解析,列出每个单词的出现情况以及找到的相应行。我现在已经完成了这个项目,希望通过阅读其他人对STL的使用来优化我的代码(我们应该在很大程度上依赖STL来完成这个任务) 这不是关于家庭作业本身,而是我在每个单词中做了两次尝试,结果导致流吃掉了我的新词。如果没有它们,我就无法跟踪我正在阅读的文档中的哪一行,因此就无法使用此类解决方案 尝试一: string word; stringstream ss; ss << document; //

对于我的家庭作业项目,我必须阅读一本书,然后逐字解析,列出每个单词的出现情况以及找到的相应行。我现在已经完成了这个项目,希望通过阅读其他人对STL的使用来优化我的代码(我们应该在很大程度上依赖STL来完成这个任务)

这不是关于家庭作业本身,而是我在每个单词中做了两次尝试,结果导致流吃掉了我的新词。如果没有它们,我就无法跟踪我正在阅读的文档中的哪一行,因此就无法使用此类解决方案

尝试一:

string word;
stringstream ss;
ss << document; // Document was read from file and stored in a "string document"
while(ss)
{
    ss >> word;
    // Work with the word.
    // Oops! No newlines anymore! :(
}
字符串字;
细流ss;
ss>word;
//使用单词。
//哎呀!不再换行了!:(
}
尝试二:

ifstream ifs(filename.c_str());
if(ifs.is_open)
{
    typedef istream_iterator<string> string_input;
    vector<string> words;
    copy(string_input(ifs), strin_input(), back_inserter(words));

    // Oops! The newlines are gone here too! :(
}
ifstreamifs(filename.c_str());
如果(如果开放)
{
typedef是流迭代器字符串输入;
向量词;
复制(字符串输入(ifs)、字符串输入();
//哎呀!这里的新词也不见了!:(
}
我目前的解决方案并没有我想要的那么漂亮,我想要更多的STL魔术(只是为了学习一些简单的STL技巧,让它更舒服)

当前解决方案:

读取文件:

std::ostringstream os;
ss << ifstream(filename.c_str()).rdbuf();
return ss.str();
std::ostringstream操作系统;

ss您可以逐行解析单词:

std::string line;
vector<string> words;

while(std::getline(ifs, line))
{
    std::stringstream linestream(line);

    copy(std::istream_iterator<std::string>(linestream),
         std::istream_iterator<std::string>(),
         std::back_inserter(words));

    ++lineCount;
}
std::字符串行;
向量词;
while(std::getline(ifs,line))
{
std::stringstream linestream(行);
复制(std::istream_迭代器(linestream),
std::istream_迭代器(),
标准:背向插入器(单词);
++行数;
}

York:谢谢你的回答!虽然这肯定会起作用,但它会使我当前的程序设计无效。我使用文件管理器来管理从文件中读取文档,然后使用单独的类来管理单个单词。使用此解决方案,我必须在返回该单词时跟踪该行,否则我将必须立即开始处理该函数中的每个单词。+1是一个很好的解决方案。不就是用std::ios::binary work打开流吗?
std::string line;
vector<string> words;

while(std::getline(ifs, line))
{
    std::stringstream linestream(line);

    copy(std::istream_iterator<std::string>(linestream),
         std::istream_iterator<std::string>(),
         std::back_inserter(words));

    ++lineCount;
}