【发布时间】:2018-03-07 07:14:30
【问题描述】:
我正在尝试从文本文件中读取这些行,然后将每一行分解为一个单词向量。接下来,我需要从每个向量中获取第一个单词。以下是我的代码
#include<bits/stdc++.h>
using namespace std;
int main (){
ifstream inputFile("input.txt");
vector<string> words;
string line, piece;
while( getline(inputFile, line) ){
istringstream lineStream(line);
while( getline(lineStream, piece, ' ') ){
words.push_back(piece);
}
// this does not work
cout << words.front() << endl;
/*
// this works fine
for(unsigned int i=0; i<words.size(); i++){
cout << words[i] << endl ;
}
*/
words.clear();
}
return 0;
}
这是文本文件包含的内容
Read the lines from a file
Break each line into words
print the 1st word from each of those lines
此行导致错误
cout << words.front() << endl;
我需要这样的输出
Read
Break
print
请有人帮忙!
【问题讨论】:
-
您尝试
cout << words[0] << endl;获取第一个元素吗?您还应该确保向量不为空。 -
您几乎肯定不应该包含
bits/stdc++.h- 以bits开头的任何内容都是内部“特定于实现”的标头,并且a)不可移植,b)不一定“完整”。 -
除了@mch:
words[0]以及words.front()如果words.empty()返回true将失败(可能崩溃)。因此,这应该事先检查。 -
非空技巧奏效了。非常感谢@mch
-
你真的应该避免
using namespace std- 这是一个坏习惯,当你不期待它时can silently change the meaning of your program。习惯于使用命名空间前缀(std故意很短),或者将只是您需要的名称 导入到最小的合理范围。此外,在此处发布代码时请坚持使用标准 C++ 标头 -<bits/stdc++.h>是特定于平台的,会减少可能回答的人数。
标签: c++ vector file-handling