【问题标题】:How would I search each word of user input in a text file如何在文本文件中搜索用户输入的每个单词
【发布时间】:2014-04-01 15:33:57
【问题描述】:
char option;
cout <<"What langauge would you like to translate from - English 'E' or French 'F': ";
cin >> option;
cin.ignore();

ifstream in;
in.open("Q3.dic");
size_t pos;
string phrase;
if (option == 'E')
{
    cout <<"please enter a sentence in English: ";
    getline(cin, phrase);
    for(string english, french; 
    getline(in, english, '\t') && getline(in, french);
    )
    {
        pos = english.find(phrase);
        if(pos != string::npos)
        {
            cout << french <<endl;
            break;
        }
    //cout << english << '\t' << french <<endl;
    }
}
else if (option == 'F')
{
    cout <<"please enter a sentence in French: ";
    getline(cin, phrase);
    for(string english, french; 
    getline(in, english, '\t') && getline(in, french);
    )
    {
        pos = french.find(phrase);
        if(pos != string::npos)
        {
            cout << english <<endl;
            break;
        }
    //cout << english << '\t' << french <<endl;
    }
}
in.close();
cout <<endl;

system("pause");
return 0;

}

现在我的代码只有在我只输入一个单词时才有效。但是如果我输入一个句子,它不会输出任何东西。

所以我的问题是如果用户输入:你好早上好,我将如何在我的文本文件中搜索你好和早上好并输出它。

这是一个文本文件的例子:

今天天亮

祝你好运

早安你好

午后时间

晚安晚安

非常漂亮

【问题讨论】:

标签: c++


【解决方案1】:

看起来您需要一个三步流程:
1) 读入一行文本。
2) 从文本字符串中提取英文单词。
3) 从文本字符串中提取法语单词。

您应该研究一个很好的数据结构:std::istringstream。这允许您将字符串视为输入流。

另一种方法是使用std::stringfind方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多