[英]How do i only read the second word from the .txt file
我想從打開的文本文件中讀取並提取演員姓氏。
我試圖這樣做,但是它只能從句子中讀出每隔一個單詞。
演員姓氏以分號結尾,但我不知道該如何進行。
(我不想使用向量,因為我不太了解它們)
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;
}
}
}
}
假設文件的每一行包含兩個用空格分隔的單詞(第二個單詞以分號結尾),下面是示例如何從此類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
方法所需的開始索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.