首页 > 试题广场 >

编写一个程序,它要求用户首先输入其名,然后输入其姓;然后程序

[问答题]
编写一个程序,它要求用户首先输入其名,然后输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用char数组和头文件cstring中的函数。下面是该程序运行时的情形:
Enter your first name: Flip
Enter your last name: Fleming
Here's the information in a single string: Fleming, Flip

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
 char name[40];
 char fname[20];
 char lname[20];
 cout<<"Enter your first name: ";
 cin>>fname;
 cout<<"Enter your last name: ";
 cin>>lname;
 strcat(name,fname);
 strcat(name,", ");
 strcat(name,lname);
 cout<<"Here's the information in a single string: "<<name;
 return 0;
}

发表于 2019-02-02 13:38:05 回复(1)
#include<iostream>
using namespace std;
int main()
{
 char name[40]="NULL";
    char fname[20];
    char lname[20];
cout<<"Enter your first name: ";
cin>>fname;
cout<<"Enter your last name: ";
cin>>lname;
for (int i = 0; i <(strlen(lname)+strlen(fname)+1); i++)
{
    if (i < strlen(lname)) { name[i] = lname[i]; }
    if (i == strlen(lname)) { name[i] = ','; }
    if(i>strlen(lname)) { name[i] = fname[i - strlen(lname)-1]; }
}
cout<<"Here's the information in a single string: "<<name;
return 0;
}
编辑于 2020-10-16 14:25:24 回复(0)