我目前正在自学 C/C++,并且我得到了练习(来 self 正在阅读的书)来编写一个可以产生如下输出的程序:
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;
}
最佳答案
首先,没有 C/C++ 这样的东西。你在混合它们,这是错误的。由于您使用的是 C++ header /new
/using
,因此我假设您需要 C++,因此请按以下方式修复代码:
- 将所有
char*
和char[]
替换为std::string
- 摆脱动态分配
因此,一些更改将是:
struct Person {
std::string firstName;
std::string lastName;
};
或
Person ps;
关于c++ - 输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13138169/