首页 文章

我如何只读取.txt文件中的第二个单词

提问于
浏览
0

我想从打开的文本文件中读取并提取actor Surname .

我试着这样做,但它只能从句子中读出所有其他单词 .

Actors姓氏以分号结尾,但我不知道如何继续 .

(我不想使用矢量,因为我不完全理解它们)

bool check=false;

while (!check) //while false
{
    string ActorSurname = PromptString("Please enter the surname of the actor:");


    while (getline (SecondFile,line)) //got the line. in a loop so keeps doing it 
    {
        istringstream SeperatedWords(line);  //seperate word from white spaces
        string WhiteSpacesDontExist;
        string lastname;

            while (SeperatedWords >> WhiteSpacesDontExist >> lastname) //read every word in the line //Should be only second word of every line
            {
                //cout<<lastname<<endl;
                ToLower(WhiteSpacesDontExist);

                if (lastname == ActorSurname.c_str()) 

                {
                    check = true;
                }
        }

    }
}

1 回答

  • 0

    假设文件的每一行包含两个用空格分隔的单词(第二个单词以分号结尾),下面是如何从这样的 string 读取第二个单词的示例:

    #include <string>
    #include <iostream>
    
    int main()
    {
        std::string text = "John Smith;"; // In your case, 'text' will contain your getline() result
        int beginPos = text.find(' ', 0) + 1; // +1 because we don't want to read space character
        std::string secondWord;
        if(beginPos) secondWord = text.substr(beginPos, text.size() - beginPos - 1); // -1 because we don't want to read semicolon
        std::cout << secondWord;
    }
    

    输出:

    Smith
    

    在这个例子中,我们使用 std::string 类的方法 find . 此方法返回我们查找的字符的位置(如果未找到字符,则返回 -1 ),我们可以使用它来确定 substr 方法中所需的开始索引 .

相关问题