0

I have a struct called Person:

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

So I want to enter as many Person as I want with the standard input in one line of the following form:

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

So I did write this code but it doesn't give me what I'm looking for:

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);
}

How can I correct my code to satisfy my need?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
makaw
  • 1
  • 1
  • What's the value of `r` and why are you using `scanf`? – Bob__ Jul 24 '21 at 08:28
  • Google `std::cin` – Igor R. Jul 24 '21 at 08:29
  • because I want the following format [ , , ] – makaw Jul 24 '21 at 08:30
  • Can you spot the difference between [1](https://godbolt.org/z/a97rYqzaj) and [2](https://godbolt.org/z/deqn1K61K) (or [3](https://godbolt.org/z/c57313rc1))? – Bob__ Jul 24 '21 at 08:45
  • oh why the value of r is changed? – makaw Jul 24 '21 at 08:55
  • Probably there is a space or a newline in your input, one that is not taken into account by the format string your code passed to `scanf`. Try [this](https://godbolt.org/z/Yj5cxerqn) and then I'd suggest you to search for safer alternatives. – Bob__ Jul 24 '21 at 09:05
  • thanks, and how to verify if I entered { instead of [ I want the program to give me an error if so – makaw Jul 24 '21 at 09:20
  • 1
    Well, there are plenty of ways: https://stackoverflow.com/questions/51977400/how-do-i-check-if-a-string-format-is-valid-while-reading-from-a-text-file-in-c/51977833 https://stackoverflow.com/questions/38672532/check-if-string-matches-a-particular-format https://stackoverflow.com/questions/24276482/how-to-check-if-users-input-is-valid-c , starting from checking the value returned by `scanf`, which is the number of fields that were successfully converted and assigned. – Bob__ Jul 24 '21 at 09:26

1 Answers1

0

You can use std::cin instead of 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);
}

  • 1
    This accepts `id age salary id age salary ...` instead of `[id, age, salary] [id, age, salary] ...` – 0x5453 Jul 26 '21 at 19:42