c++从文件中读取用空格和新行分隔的单词
C++ reading in from file with words seperated by whitespace and new lines
我遇到了一个问题,从一个文件中读取由空格分隔的单词,并随机添加新行。下面是我的代码:
vector<string> _vecIgnoreWords;
vector<string> _vecHungerGames;
void readTextFile(char *fileNameHungerGames, vector<string>& _vecHungerGames){
ifstream fileInHungerGames;
string newline;
fileInHungerGames.open(fileNameHungerGames);
if(fileInHungerGames.is_open()){
while(getline(fileInHungerGames, newline)){
stringstream iss(newline);
while(iss){
iss >> newline;
if(!(isCommonWord(newline, _vecIgnoreWords))){
_vecHungerGames.push_back(newline);
cout << newline << endl;
}
}
}
fileInHungerGames.close();
}
main中的调用:
string fileName = argv[2];
string fileNameIgnore = argv[3];
char* p = new char[fileNameIgnore.length() + 1];
memcpy(p, fileNameIgnore.c_str(), fileNameIgnore.length()+1);
getStopWords(p, _vecIgnoreWords);
char* hungergamesfile_ = new char[fileName.length() + 1];
memcpy(hungergamesfile_, fileName.c_str(), fileName.length()+1);
readTextFile(hungergamesfile_, _vecHungerGames);
停止词void:
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
ifstream fileIgnore;
string line;
fileIgnore.open(ignoreWordFileName);
if(fileIgnore.is_open()){
while(getline(fileIgnore, line)){
_vecIgnoreWords.push_back(line);
}
}
fileIgnore.close();
return;
}
我目前的问题是,我的输出这段代码结束类似于:
bread
is
is
slipping
away
take
我不知道为什么我得到重复(is is)和空行,当我使用字符串流?
我的输出应该看起来像:
bread
is
slipping
away
from
me
也稍微不那么重要,但是我的while循环是循环一次太多这就是为什么我有if(_vecHungerGames.size() == 7682)
有没有办法修复这个循环,从循环一次太多?
文件的例子:
bread is
slipping away from me
i take his hand holding on tightly preparing for the
试试这样:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
std::vector<std::string> _vecIgnoreWords;
std::vector<std::string> _vecHungerGames;
void getStopWords(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (std::getline(file, s))
output.push_back(s);
}
void readTextFile(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (file >> s)
{
if (!isCommonWord(s, _vecIgnoreWords))
{
output.push_back(s);
std::cout << s << std::endl;
}
}
}
int main()
{
getStopWords(argv[3], _vecIgnoreWords);
readTextFile(argv[2], _vecHungerGames);
// use _vecHungerGames as needed...
return 0;
}
相关文章:
- 使用新行和不使用新行读取文件
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 遇到新行时,有没有办法停止istream_iterator
- PangoLayout 中忽略的新行
- 使用 clang 格式时,当行很大时,如何将右括号分成新行?
- 如何检测将文本文件读入 int 数组的新行
- 当 getline 直到新行才读取时会发生什么?
- 添加新行时工作代码引发异常.调试技巧?
- QTree查看新行,没有布局就不可见已更改
- 嵌套结构,从由空行分隔的文件中读取数据
- 新行上的 clang 格式右括号
- C++流:保存到新行而不是覆盖旧行
- (C++) 使用诅咒打印从文件中读入的新行
- 按升序输出整数时,将最后一个整数放在新行上
- 用C++计算输入文本的新行数
- 在C++中打印用新行分隔的6,5,4,3,2个字符
- c++将行getline放入数组中,用新行分隔
- 如何在c++中有效地读取新行分隔的整数
- c++从文件中读取用空格和新行分隔的单词