您拥有最终用户输入的特殊符号,因此您可以要求输入,直到获得此符号(“。”)。代码可以是这样的:
while(true)
{
std::string name;
std::cin >> name;
if(name == ".")
break;
// number of services
size_t n = 0;
std::cin >> n;
// list of services
std::vector<std::string> services(n);
for(size_t i = 0; i < n; ++i)
std::cin >> services[i];
// Here you can process user
// You know user's name and have std::vector of his services
}
此代码无限循环,直到用户名等于“.”。
如果要输出所有用户或在列表中处理它们,则必须将它们存储在向量中。
struct User
{
User(const std::string& _name):
name(_name)
{
}
std::string name;
std::vector<std::string> services;
};
std::vector<User> users;
int main( )
{
std::vector<User> users;
while(true)
{
std::string name;
std::cin >> name;
if(name == ".")
break;
users.push_back(User(name));
size_t n = 0;
std::cin >> n;
for(size_t i = 0; i < n; ++i)
{
std::string serviceName;
std::cin >> serviceName;
users.back().services.push_back(serviceName);
}
}
for(size_t n = users.size(), i = 0; i < n; ++i)
{
std::cout << users[i].name;
std::cout << " ";
std::cout << users[i].services.size();
std::cout << " ";
for(size_t s = users[i].services.size(), j = 0; j < s; ++j)
std::cout << users[i].services[j] << " ";
std::cout << std::endl;
}
return 0;
}
此代码读取用户及其服务,然后将其打印回来。
如果您知道每个用户都在不同的行上,则可以有另一种方式来读取每个用户。
std::string l;
std::getline(std::cin, l);
std::istringstream ss(l);
std::string name;
ss >> name;
if(name == ".")
break;
users.push_back(User(name));
size_t n = 0;
ss >> n;
for(size_t i = 0; i < n; ++i)
{
std::string serviceName;
ss >> serviceName;
users.back().services.push_back(serviceName);
}
我正在从输入流(cin)中读取整行,然后创建字符串流(ss)并从中读取用户信息。