2017-02-19 124 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);