我希望根据用户在不同行中输入的内容获得一个特定的元素。我对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‘兄弟姐妹并输入Mark,John,Susan,我如何获得第二个兄弟姐妹的名字- "John"?或者名字是输入的还是最后输入的?
**此外,我希望这个问题只需问一次,然后等待用户根据他们在不同行上放置的内容输入X个兄弟姐妹,然后继续进行程序,但问题是反复提出的。
发布于 2014-01-18 06:31:09
首先,您应该将siblings定义为int而不是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。
https://stackoverflow.com/questions/21200679
复制相似问题