将struct传递给vector,打印vector给出了奇怪的结果

时间:2017-02-19 19:34:05

标签: c++ vector struct

考虑以下计划。基本上我有一个名为Person的struct,默认包含name="NO NAME"age = 0。现在我首先创建一个向其添加5 Person的向量。甚至在调试器中运行,在for循环结束后只有5个大小的向量,默认为Person。然而,当我去打印时,出了点问题。

我首先传递const向量,因为我没有改变任何东西。使用printf,我执行此操作:list_of_persons.at(i).name, list_of_persons.at(i).age,只打印出此人的姓名和年龄。你会期望它是NO NAME0,因为我没有更改默认值,但我的cmd给了我一些不同的东西,我不知道为什么?

enter image description here

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main();

struct Person {
    string name = "NO NAME";
    int age = 0;
};

void print_vector(const vector <Person> &);

int main()
{
    vector<Person> list_of_persons;
    for (unsigned int i = 0; i < 5; i++)
    {
        struct Person p;
        list_of_persons.push_back(p);
    }
    print_vector(list_of_persons);

    printf("\n");

    system("pause");
    return 0;
}

void print_vector(const vector<Person>& list_of_persons)
{
    for (unsigned int i = 0; i < list_of_persons.size(); i++)
    {
        printf("Person %d \n", i);
        printf("Name: %s\nAge: %d \n \n", list_of_persons.at(i).name, list_of_persons.at(i).age);
    }
}

1 个答案:

答案 0 :(得分:3)

您正在将C ++与printf C函数混合使用。 printf无法知道您在此处传递的内容不是字符串,因为printf的参数是变量并且函数“信任”格式化字符串&amp;调用者提供适当的类型。

您看到的是char *对象的std::string表示形式:按原样打印时的二进制数据/垃圾(并且由于参数大小不正确而会破坏age参数)< / p>

您应该使用std::cout中的iostream来正确识别std::string类型。比如这样:

std::cout << "Name: " << list_of_persons.at(i).name << "\nAge: " << list_of_persons.at(i).age << "\n \n";

如果您想坚持printf,则必须使用const char *

获取基础c_str()上的指针
printf("Name: %s\nAge: %d \n \n", list_of_persons.at(i).name.c_str(), list_of_persons.at(i).age);