如何在 c++ 中从文本文件中获取特定单词?
How to get a specific word from a text file in c++?
我正在尝试从.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;
}
如果您仍然有问题,请告诉我:)
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何在 c++ 中从文本文件中获取特定单词?
- 如何获取句子中单词的第一个字母*没有*指针,引用等
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 用于获取以元音和辅音开头的单词数量的程序返回错误的答案
- 如何在 c++ 中从文本文件的正文中获取特定的单词和行
- QTEXTEDIT:在鼠标指针下获取单词
- 从两个单词之间获取字符串
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- C++如何在两个单词之间获取字符串/字符
- 获取字符串的第一个单词并从实际字符串中删除该单词
- 从多行代码中获取单词C++
- 从vector和unordered_map中获取三个出现次数最多的单词及其计数值
- 使用c++获取字符串中每个单词的第一个字母
- 获取字符'='之前的所有标准::字符串或第一个单词
- 从字符串中获取一个单词,对其进行更改,然后将其放回正确的位置
- 获取字符串输入以创建单词
- 这个算法获取所有单词梯的时间复杂度是多少?
- 在c++中从字符串中获取每个单独的单词