如何在文档中搜索 c++ 中的字符串?

发布于 2024-08-27 18:48:20 字数 994 浏览 3 评论 0原文

到目前为止,这是我的代码:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
    int count = 0;
    string fileName;
    string keyWord;
    string word;


    cout << "Please make sure the document is in the same file as the program, thank you!" 
         << endl << "Please input document name: " ;
    getline(cin, fileName);
    cout << endl;

    cout << "Please input the word you'd like to search for: " << endl;
    cin >> keyWord;
    cout << endl;
    ifstream infile(fileName.c_str());
    while(infile.is_open())
    {
        getline(cin,word);
        if(word == keyWord)
        {
            cout << word << endl;
            count++;
        }
        if(infile.eof())
        {
            infile.close();
        }

    }
    cout << count;

}

我不确定如何转到下一个单词,目前是无限循环......有什么建议吗?

另外...我如何告诉它打印出该单词所在的行?

提前致谢!

Here's my code so far:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
    int count = 0;
    string fileName;
    string keyWord;
    string word;


    cout << "Please make sure the document is in the same file as the program, thank you!" 
         << endl << "Please input document name: " ;
    getline(cin, fileName);
    cout << endl;

    cout << "Please input the word you'd like to search for: " << endl;
    cin >> keyWord;
    cout << endl;
    ifstream infile(fileName.c_str());
    while(infile.is_open())
    {
        getline(cin,word);
        if(word == keyWord)
        {
            cout << word << endl;
            count++;
        }
        if(infile.eof())
        {
            infile.close();
        }

    }
    cout << count;

}

I'm not sure how to go to the next word, currently this infinite loops...any recommendation?

Also...how do I tell it to print out the line that that word was on?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七婞 2024-09-03 18:48:20
while(infile >> word)
{
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}

这样就可以完成任务了。请阅读更多关于流的内容。

while(infile >> word)
{
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}

This would do the job. Please read about streams more.

还在原地等你 2024-09-03 18:48:20

如果您只想计算文件中关键字的数量,那么:

int count = std::count(std::istream_iterator<std::string>(infile),
                       std::istream_iterator<std::string>(),
                       keyword);

如果您想读取单词。
但也想打印行号,那么这样的事情应该可以工作:

std::string      line;
std::ifstream    infile("plop");
int              lineNumber = 0;

while(std::getline(infile, line)) 
{
    ++lineNumber ;
    std::stringstream   linestream(line);
    int hits = std::count(std::istream_iterator<std::string>(linestream),
                          std::istream_iterator<std::string>(),
                          keyword);
    if (hits != 0)
    {
        std::cout << "Line: " << lineNumber << "   Matches(" << hits << ")\n";
    } 
    count  += hits;
} 

If all you want to do is count the number of keywords in a file then:

int count = std::count(std::istream_iterator<std::string>(infile),
                       std::istream_iterator<std::string>(),
                       keyword);

If you want to read words.
But also want to print the line numbers then somthing like this should work:

std::string      line;
std::ifstream    infile("plop");
int              lineNumber = 0;

while(std::getline(infile, line)) 
{
    ++lineNumber ;
    std::stringstream   linestream(line);
    int hits = std::count(std::istream_iterator<std::string>(linestream),
                          std::istream_iterator<std::string>(),
                          keyword);
    if (hits != 0)
    {
        std::cout << "Line: " << lineNumber << "   Matches(" << hits << ")\n";
    } 
    count  += hits;
} 
谈场末日恋爱 2024-09-03 18:48:20

问题出在源代码的这一部分:

getline(cin,word);

if(word == keyWord)
{
    cout << word << endl;
    count++;
}

首先,您不想读取cin中的行。您想要从infile读取单词。因此,您应该将循环内代码的第一行替换为:

infile >> word;
if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }

另外,您应该更改循环的条件。您无需在此处检查infile是否已打开。您应该在循环开始之前检查这一点。对于循环,您需要检查是否已达到 eof 状态:

if ( !infile.is_open() ) {
    cerr << "Error while opening file." << endl;
    exit( EXIT_FAILURE );
}    

while( !infile.eof() ) {
    infile >> word;
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}

正如您所看到的,现在您可以摆脱您输入的那个奇怪的第二个 if循环内。

最后一步是介绍“预读”技术:当我们没有读到任何内容时,测试 eof 是没有意义的。

if ( !infile.is_open() ) {
    cerr << "Error while opening file." << endl;
    exit( EXIT_FAILURE );
}    

infile >> word;    
while( !infile.eof() ) {
    if( word == keyWord )
    {
        cout << word << endl;
        count++;
    }

    infile >> word;
}

希望这有帮助。

The problem comes in this part of the source code:

getline(cin,word);

if(word == keyWord)
{
    cout << word << endl;
    count++;
}

First of all, you don't want to read lines from cin. You want to read words from infile. So you should replace the first line of your code inside the loop by:

infile >> word;
if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }

Also, you should change the condition of the loop. You don't need to check if the infile is open here. You should check for that before the loop starts. For the loop, you need to check whether the eof state has been reached or not:

if ( !infile.is_open() ) {
    cerr << "Error while opening file." << endl;
    exit( EXIT_FAILURE );
}    

while( !infile.eof() ) {
    infile >> word;
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}

And as you can see, now you can get rid off that strange second if you put inside the loop.

Last step is to introduce the "reading ahead" technique: it does not make sense to test for eof when we haven't read anything.

if ( !infile.is_open() ) {
    cerr << "Error while opening file." << endl;
    exit( EXIT_FAILURE );
}    

infile >> word;    
while( !infile.eof() ) {
    if( word == keyWord )
    {
        cout << word << endl;
        count++;
    }

    infile >> word;
}

Hope this helps.

少跟Wǒ拽 2024-09-03 18:48:20

while(infile.is_open()) 更改为 while(infile)。然后你可以删除最后多余的eof测试。

即使您遇到错误或到达文件末尾,它仍然处于打开状态。您可能处于这样一种情况:failbit 已设置(getline 不返回任何内容),但尚未遇到 eof,因此文件永远不会关闭,因此您的循环永远不会退出。使用流的 operator bool 可以为您解决所有这些问题。

Change while(infile.is_open()) to while(infile). Then you can remove the redundant eof test at the end.

It's still open even if you've encountered an error or reached the end of file. It's likely you are in a scenario where failbit is getting set (getline returns nothing), but eof has not been encountered, so the file never gets closed, so your loop never exits. Using the operator bool of the stream gets around all these problems for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文