我如何只从 .txt 文件中读取第二个单词
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;
}
}
}
}
假设文件的每一行包含两个用 space 分隔的单词(第二个单词以分号结尾),下面是如何从 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
class 的方法 find
。此方法 returns 我们查找字符的位置(或 -1
如果未找到字符),我们可以使用它来确定 substr
方法中所需的开始索引。
我想从打开的文本文件中读取并提取演员的姓氏。
我试过这样做,但它只能从句子中读取每个其他单词。
演员姓氏以分号结尾,但我不知道如何继续。
(我不想使用向量,因为我不完全理解它们)
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;
}
}
}
}
假设文件的每一行包含两个用 space 分隔的单词(第二个单词以分号结尾),下面是如何从 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
class 的方法 find
。此方法 returns 我们查找字符的位置(或 -1
如果未找到字符),我们可以使用它来确定 substr
方法中所需的开始索引。