【发布时间】:2020-10-11 23:11:10
【问题描述】:
我正在尝试读取包含某人信息(姓名、年龄、职业)的文本文件,如下所示:
name 20
occupation
name 25
occupation
name 34
occupation
我阅读了整个文件,并且对于每一行我使用istringstream 跳过名称和年龄之间的空格。
std::vector<string> readfile(std::vector<std::string> *words, char *argv){
std::ifstream file(argv); //Opens the file specified on execution
if ( !file ){
cerr << "Le fichier " << argv << " n'existe pas" << endl;
exit (-1);
} else {
std::string line;
while (std::getline(file, line)){
istringstream ss(line);
do {
string word;
ss >> word;
if (word != " " || word != "\n"){
words->push_back(word);
};
} while (ss);
};
file.close();
};
return *words;
};
我的主要是:
int main( int argc, char *argv[] ){
std::vector<std::string> compV;
readfile(&compV,argv[1]);
cout << compV.at(2) << endl;
return 0
}
当我编译并执行程序时,我得到一个空格作为结果。
compV.at(0) 显示名称
comV.at(1) 显示年龄
但是comV.at(2) 显示的是空格而不是占用。
我在这里做错了什么?
【问题讨论】:
-
为什么要打开文件两次?
word != " " || word != "\n"永远不会是false。 -
哦,我实际上并没有纠正那个,我的错
标签: c++ string c++11 vector istringstream