我需要输入3个以逗号分隔的全名
全名 1:约翰、史密斯、弗林
全名 2:沃尔特、肯尼迪、罗伯茨
全名 3:Sam、Bass、Clinton
然后这样输出
名字 1:约翰
名字 2:沃尔特
名字 3:山姆
中间名 1:史密斯
中间名 2:肯尼迪
中间名 3:低音
姓氏 1:弗林
姓氏 2:罗伯茨
姓氏 3:克林顿
我该怎么做? 到目前为止,这是我的代码
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main () {
char first[3][100];
char middle[3][100];
char last[3][100];
char full[3][100];
int i;
cout << "Enter 3 Full Names <first, middle and last names separated by comma>:" << endl;
for (i=0; i<3; i++) {
cout << "Full Name " << i+1 << ":" ;
gets (full[i]);
}
cout << "The first names are: " << endl;
for (i=0; i<3; i++) {
strcpy (first[i], full[i]);
if (strcmp (first[i], ", ")) {
cout << "First Name "<< i+1 << ":" ;
strcpy ( first[i], full[i] );
cout << (first[i]);
cout << endl;
}
}
cout << "The middle names are: " << endl;
for (i=0; i<3; i++) {
cout << "Middle Name "<< i+1 << ":" ;
cout << (middle[i]);
cout << endl;
}
cout << "The last names are: " << endl;
for (i=0; i<3; i++) {
cout << "Last Name "<< i+1 << ":" ;
cout << (last[i]);
cout << endl;
}
system("pause");
return 0;
}
最佳答案
我想这里你想要的是字符串类的拆分方法,该方法应该是这样的:
void SplitName(const string& fullName, const string& delims, vector<string>& names)
{
size_t i = 0;
size_t j = 0;
while (i < fullName.size())
{
i = fullName.find_first_not_of(delims, i);
j = fullName.find_first_of(delims, i);
if (i < fullName.size())
{
names.push_back(fullName.substr(i, j - i));
}
i = j;
}
}
您可以将“:”定义为delims,那么names[1]是First Name,names[2]是Middle Name,names[3]是Last Name。
关于c++ - 将单个字符串分成多个字符串 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5088358/