我现在正在自学 C/C++,并且我得到了练习(来自我正在阅读的书)来编写一个可以产生如下输出的程序:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip
使用结构。但我的输出是这样的:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: ,
这是代码。它相当简短,所以应该不难阅读:)
#include <iostream>
#include <cstring>
using namespace std;
struct Person {
char* firstName;
char* lastName;
};
char* getName(void);
int main() {
Person* ps = new Person;
cout << "Enter your first name: ";
char* name;
name = getName();
ps->firstName = name;
cout << "Enter your last name: ";
char* lastname;
lastname = getName();
ps->lastName = lastname;
cout << "Here's the information in a single string: "
<< ps->lastName << ", " << ps->firstName;
delete ps;
delete name;
delete lastname;
return 0;
}
char* getName() {
char temp[100];
cin >> temp;
cin.getline(temp, 100);
char* pn = new char[strlen(temp) + 1];
strcpy(pn, temp);
return pn;
}