c++ - 查找以用户输入符号开头的单词并计算它们是 C++ 的文本行
问题描述
我有一个练习,我需要在以用户输入符号开头的文本文件中查找单词。我还需要确定该单词在哪一行,并将其输出到不同的文本文件中。我设法编写代码以输出以符号开头的单词并计算单词在文本中的位置,但我无法弄清楚如何计算该单词在哪一行。我还需要找到那些具有诸如?
!
等符号的单词。' '
例如,如果我想查找以开头的单词,c
那么我的程序从我的示例中仅找到“cerebral, cortex, could, create”而不是“construct, able, computer”输入在我的代码下方。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream input;
fstream output;
string word, line;
char startOfWord;
cout << "I wanna find words starting with symbol: \n";
cin >> startOfWord;
int lineNumber = 0;
input.open("f.txt");
output.open("f1.txt");
while (!input.eof()) {
input >> word;
lineNumber++;
if (word.length() > 40) {
continue;
}
if (word[0] == startOfWord) {
output << word << ' ' << lineNumber << '\n';
}
}
input.close();
output.close();
return 0;
}
示例输入:用户想要查找以 . 开头的单词a
。
f.txt:
A Stanford University project to?construct a model
of the cerebral cortex in silicon could help scientists
gain a better understanding of the brain, in order to
create more,capable.computers and advanced
neural prosthetics.
输出:f1.txt
a 1
a 3
and 4
advanced 4
解决方案
为了在不为您完成练习的情况下为您指明正确的方向,您可以通过std::ifstream
and使用一些函数std::basic_istream
,该类std::ifstream
继承了它的许多功能。
std::ifstream::getline()
std::ifstream::get()
std::ifstream::peek()
std::ifstream::putback()
这些函数处理捕获整行输入、从输入流中读取字符、查看字符而不从流中提取字符以及将字符放回流中。
所有这些都可以在C++ 文档站点上找到std::ifstream
。
推荐阅读
- error-handling - 有什么方法可以快速查看所有现有的 SSIS 包事件处理程序?
- html - 为什么我的 Bootstrap 示例页面中的轮播不起作用?
- django - 显示内联时更改 Django Admin 的“添加另一个 SomeObject”按钮上的文本
- string - 为什么使用 -n 测试非空字符串总是正确的?
- java - SimpleDateFormat 对象更改时区而不添加/减去正确的小时数
- reactjs - React Jest:如何模拟返回数据的异步 API 调用?
- python - ImportError:无法从“树”导入名称“_assert_shallow_structure”
- postgresql - 如何为 postgres 安装 plpython?
- javascript - 循环遍历数组并显示数据
- azure - 如何使用azure-ad-b2c自定义登录页面的html和css