2014-01-18 47 views
0

我想根據用戶在不同行中輸入的內容獲取某個元素。我是C++編程的新手,所以我不確定要採取什麼路線。如何從多個輸入中獲取某個元素C++

std::string siblings; 
std::string names; 

std::cout << "Please enter how many siblings you have: "; 
std::cin >> siblings; 

for (int x=0;x<siblings;x++){ 
    std::cout << "Please enter your sibling(s) name: "; 
    std::cin >> names; 
} 

因此,如果用戶輸入「3」兄弟姐妹,鍵入馬克,約翰,蘇珊,我如何得到第2個兄弟姐妹的名字 - 「約翰」?或者,也許輸入的第一個名字,或最後?

**另外,我想問一個問題,等待用戶根據他們放在不同的線上的X數量的兄弟姐妹,然後繼續進入程序,但問題是反覆詢問。

+1

如何聲明'names'? – DavidO

+0

你知道'Array'嗎? –

+0

@VedantTerkar,我不知道。什麼是陣列? – Shoe

回答

1

首先,你應該定義siblingsint,而不是std::string,否則你在for循環使用operator<,將無法正常工作。其次,您應該使用std::vector並在for循環內推送名稱。下面是完整的工作代碼:

int siblings = 0; 
std::vector<std::string> names; 

std::cout << "Please enter how many siblings you have: "; 
std::cin >> siblings; 

for (int x = 0; x < siblings; x++) { 
    std::string current; 
    std::cout << "Please enter the name for sibling #" << (x + 1) << ':'; 
    std::cin >> current; 
    names.emplace_back(current); 
} 

上面的代碼會問兄弟姐妹的號碼,然後會要求每一個同級的名稱,並將其推入names

如果你真的想冒險進入魔法世界的字符串格式與C和C++,take a look at this other question

+0

列表與矢量有什麼區別?爲什麼我不能使用列表? – Kara

+0

@Lalala,請,[閱讀此](http://stackoverflow.com/questions/2209224/vector-vs-list-in-stl)。 – Shoe

相關問題