【问题标题】:Enter values in one line (STDIN)在一行中输入值 (STDIN)
【发布时间】:2021-07-24 08:09:59
【问题描述】:

我有一个名为 Person 的结构:

Person
{
  int id;
  int age;
  int salary;
};

所以我想在以下形式的一行中使用标准输入输入任意数量的 Person:

[id, age, salary] [id, age, salary] ...

所以我确实写了这段代码,但它没有给我我想要的东西:

std::vector<Person> person;
int y = scanf("%i", &num);
for (int i = 0; i < num; i++)
{
    Person p;
    int r = scanf("[%i,%i,%i]", &p.id, &p.age, &p.salary);
    person.push_back(p);
}

如何更正我的代码以满足我的需要?

【问题讨论】:

标签: c++ vector


【解决方案1】:

你可以使用 std::cin 代替 scanf:

std::vector<Person> person;
int y;
std::cin >> y;
for (int i = 0; i < num; i++)
{
    Person p;
    std::cin >> p.id >> p.age >> p.salary;
    person.push_back(p);
}

【讨论】:

  • 这接受id age salary id age salary ... 而不是[id, age, salary] [id, age, salary] ...
猜你喜欢
  • 2020-10-25
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
相关资源
最近更新 更多