2017-02-19 112 views
0

考虑下面的程序。基本上我有一个名为Person的struct,默认为name="NO NAME"age = 0。现在我首先创建一个向其添加5 Person的向量。即使在调试器中运行,for循环结束后,它只有一个5尺寸的向量,默认为Person。但是当我去打印它时,出现了一些问题。将struct传递给vector,打印vector给出奇怪的结果

我首先通过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); 
    } 
} 
+3

C和C++是_different languages_! – ForceBru

回答

3

你混合C++与printf C函数。 printf不能知道你传递的不是字符串,因为printf的参数是变量,函数“信任”格式字符串&提供正确类型的调用方。

你看到的是std::string对象的char *表示:二进制数据/垃圾时打印为-IS(也象垃圾一样清除,因为不正确的参数大小的age参数)

您应该使用std::coutiostream,承认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);