我正在尝试从.txt文件内容中获取特定单词。假设我有一个.txt文件:
Cottage.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;
}
如果您仍有问题,请告诉我:)
关于c++ - 如何从C++中的文本文件中获取特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59309939/