c++ - 输出错误

标签 c++ cin

我目前正在自学 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/

相关文章:

c++ - 在MacOS上,简单pybind示例的编译失败

c++ - 您可以将多少数据放入堆栈?

c - 如何在 Visual Studio 中编译 Labview CIN?

c++ - 我的程序正在通过 cin.get 从之前的输入获取\n

c++ - 使用 cin.ignore 和 cin.clear C++ 时的奇怪行为

c++ - 按值对具有未知键的 map 进行排序

c++ - 区间 C++ 中的数字

c++ - 管理单个字符串的内存

c++ - cin.Getline 什么都不返回

c++ - 改变数组的值