簡體   English   中英

用C ++查找單詞

[英]Finding a word in C++

我可以在列表中找到該單詞,但是我想顯示找到該單詞后的數字。 我的名單上有名字,后面是他們的GPA。

例...

 michael 2.3 Rachel 2.5 Carlos 3.0 

我想添加一個功能,即在找到名稱后立即顯示該數字,我將其聲明為int GPA,但不確定如何將其合並到我的程序中。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string name;
    int offset;
    string line;
    int gpa;

    ifstream read_file;
    read_file.open("alpha.dat");
    cout << "Please enter your name: \n";
    cin >> name;

    if (read_file.is_open())
    {
        while (!read_file.eof())
        {
            getline(read_file, line);
            if ((offset = line.find(name)) != string::npos)
            {
                cout << "the word has been found: \n";
                // cout << name << gpa; example to display
            }
        }
        read_file.close();
        return 0;
    }

據我所知,您只需要輸出從文件中讀取的行:

while( getline(read_file, line) )
{
    if ((offset = line.find(name)) != string::npos) cout << line << endl;
}

請注意,這不是查找名稱的最佳方法。 例如,如果用戶輸入Carl怎么辦? 它會在字符串Carlos 甚至確實,如果他們輸入2 ,它將匹配多個人的GPA部分。

您可以在這里使用字符串流讀出名稱。 假設它不包含空格,這將使其與您在其中讀取用戶名的方式保持一致。順便說一下,您需要包括<sstream> 請注意,您可以讀出GPA作為該相同機制的一部分。

istringstream iss( line );
string thisname, gpa;

if( iss >> thisname >> gpa ) {
    if( thisname == name ) cout << name << " " << gpa << endl;
}

最后,您可能需要在比較字符串時考慮忽略大小寫。 厚臉皮的方法是僅使用舊的C函數。 我知道有C ++方法可以實現,但是沒有一個方法像<cstring>stricmp一樣簡單:

if( 0 == stricmp(thisname.c_str(), name.c_str()) ) {
    cout << name << " " << gpa << endl;
}

您可以使用stringstream分割line ,並將其存儲到向量中,如下所示:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    string name;
    int offset;
    string line;
    int gpa;

    ifstream read_file;
    read_file.open("alpha.dat");
    cout << "Please enter your name: \n";
    cin >> name;

    if (read_file.is_open())
    {
        while (!read_file.eof())
        {
            getline(read_file, line);
            if ((offset = line.find(name)) != string::npos)
            {
                cout << "the word has been found: \n";
                stringstream iss(line);
                vector<string> tokens;

                string str;

                while (iss >> str)
                    tokens.push_back(str);

                cout << tokens[0] << tokens[1];

            }
        }
        read_file.close();
        return 0;
    }
}

您可以將getline(read_file, line)...替換為:

read_file >> name >> gpa;
if (name == search_name)
    cout << name << " " << gpa << endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM