gpt4 book ai didi

c++ - 尝试从文本文件打印名字,但同时获取名字和中间名

转载 作者:行者123 更新时间:2023-11-30 04:41:57 26 4
gpt4 key购买 nike

<分区>

我正在尝试从格式如下的文本文件中打印名字、中间名和姓氏:

Doe, John Bob
Young, Tim Joe
Washington, George Peter

这是预期的输出:

First name: John
Middle name: Bob
Last name: Doe

First name: Tim
Middle name: Joe
Last name: Young

First name: George
Middle name: Peter
Last name: Washington

我能够正确获取中间名和姓氏,但是当我尝试获取名字时,它显示它是名字和中间名。这是代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
//Variable for the text file
ifstream infile;

//Opens the text file
infile.open("data.txt");

//Variables for the names
string name;
string lastName;
string firstName;
string middleName;

//Loops through all the names
while(getline(infile, name))
{
//Looks for a comma and space in each name
int comma = name.find(',');
int space = name.find(' ', comma+2);

//Splits the name into first, last, and middle names
lastName = name.substr(0, comma);
firstName = name.substr(comma+2, space);
middleName = name.substr(space+1, 100);

//Prints the names
cout << "First name: " << firstName << endl;
cout << "Middle name: " << middleName << endl;
cout << "Last name: " << lastName << endl;
cout << endl;
}
//closes the text file
infile.close();

return 0;
}//end main

这是我得到的输出:

First name: John Bob
Middle name: Bob
Last name: Doe

First name: Tim Joe
Middle name: Joe
Last name: Young

First name: George Peter
Middle name: Peter
Last name: Washington

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com