繁体   English   中英

如何从c ++中的文本文件中获取特定单词?

[英]How to get a specific word from a text file in c++?

我正在尝试从 .txt 文件内容中获取特定单词。 假设,我有一个 .txt 文件:

山寨.txt

1 [1] Cottage1 1000 01-10-2019 Free
2 [2] vottage2 2000 01-20-2019 Free

我想在选择 ID 为 (1) 的行时获取单词 1000 或根据用户输入获取 ID 为 (2) 的单词 2000。

我的代码: - 我知道这是不完整的,但我只是为了展示我到目前为止所做的尝试。

string GetWord(string filename)
{
    string word;
    string selectline;

    ifstream fin;
    fin.open(filename);
    cout << "Select which line to get a word from: "; //select line
    cin >> selectline;

    //some code here......

    temp.close();
    fin.close();

    return word;  
}

如果文本文件中每一行的格式都一样,那么你可以试试这个代码——

string GetWord(string filename)
{
    string word, line;
    int selectline;

    ifstream fin(filename.c_str());

    cout << "Select which line to get a word from: "; //select line
    cin >> selectline;

    int i = 1;
    while (getline(fin, line))
    {
        if(i == selectline){
            istringstream ss(line);
            for (int j=0; j<4; j++){
                ss >> word;
            }
            break;
        }
        i++;
    }

    return word;
}

如果您仍然有问题,请告诉我:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM