我想从打开的文本文件中读取演员姓氏并将其提取。
我试图这样做,但是它只能从句子中读出每隔一个单词。
演员姓氏以分号结尾,但我不知道该如何进行。
(我不想使用向量,因为我没有完全理解它们)
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;
}
}
}
}
答案 0 :(得分: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
在此示例中,我们使用find
类的方法std::string
。此方法返回我们要查找的字符的位置(如果找不到字符,则返回-1
,我们可以使用该位置来确定substr
方法中所需的开始索引。