如何从C++中的文本文件中获取特定单词?
我试图从.txt文件内容中获取特定单词。比如说,我有一个.txt文件: 小屋.txt 我希望在选择ID为1的行时获得单词1000,或者根据用户输入获得ID为2的单词2000 我的代码:-我知道这是不完整的,但我只是想展示我迄今为止所做的尝试如何从C++中的文本文件中获取特定单词?,c++,console,C++,Console,我试图从.txt文件内容中获取特定单词。比如说,我有一个.txt文件: 小屋.txt 我希望在选择ID为1的行时获得单词1000,或者根据用户输入获得ID为2的单词2000 我的代码:-我知道这是不完整的,但我只是想展示我迄今为止所做的尝试 string GetWord(string filename) { string word; string selectline; ifstream fin; fin.open(filename); cout <
string GetWord(string filename)
{
string word;
string selectline;
ifstream fin;
fin.open(filename);
cout << "Select which line to get a word from: "; //select line
cin >> selectline;
//some code here......
temp.close();
fin.close();
return word;
}
如果文本文件中每一行的格式都相同,则可以尝试此代码-
string GetWord(string filename)
{
string word, line;
int selectline;
ifstream fin(filename.c_str());
cout << "Select which line to get a word from: "; //select line
cin >> selectline;
int i = 1;
while (getline(fin, line))
{
if(i == selectline){
istringstream ss(line);
for (int j=0; j<4; j++){
ss >> word;
}
break;
}
i++;
}
return word;
}
如果仍然存在问题,请告诉我:ss来自何处?它是在if条件中声明的istringstream类类型的变量名。它将每一行作为ss变量中的一个流。它表示,不允许使用不完整的类型。请检查是否包含istringstream所需的头文件?您可以通过添加此项进行检查,包括
string GetWord(string filename)
{
string word, line;
int selectline;
ifstream fin(filename.c_str());
cout << "Select which line to get a word from: "; //select line
cin >> selectline;
int i = 1;
while (getline(fin, line))
{
if(i == selectline){
istringstream ss(line);
for (int j=0; j<4; j++){
ss >> word;
}
break;
}
i++;
}
return word;
}