如何在 c++ 中从文本文件中获取特定单词?

How to get a specific word from a text file in c++?

本文关键字:获取 单词 文件 文本 c++      更新时间:2023-10-16

我正在尝试从.txt文件内容中获取特定单词。比方说,我有一个.txt文件:

小屋.txt

1 [1] Cottage1 1000 01-10-2019 Free
2 [2] vottage2 2000 01-20-2019 Free

我想在选择 ID 为 (1( 的行时获取单词 1000,或者根据用户输入获取 ID 为 (2( 的单词 2000。

我的代码:- 我知道这是不完整的,但我只是为了展示我到目前为止所尝试的。

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;
}

如果您仍然有问题,请告诉我:)