首页 > 解决方案 > 查找以用户输入符号开头的单词并计算它们是 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

标签: c++stringchartext-filesc++20

解决方案


为了在不为您完成练习的情况下为您指明正确的方向,您可以通过std::ifstreamand使用一些函数std::basic_istream,该类std::ifstream继承了它的许多功能。

std::ifstream::getline()
std::ifstream::get()
std::ifstream::peek()
std::ifstream::putback()

这些函数处理捕获整行输入、从输入流中读取字符、查看字符而不从流中提取字符以及将字符放回流中。

所有这些都可以在C++ 文档站点上找到std::ifstream


推荐阅读