Home c++ C++ Entering an array with spaces

C++ Entering an array with spaces

Author

Date

Category

You need to enter numbers into an array through spaces.
For example:

1 12 34 5 6 -3 2

where 1 is the first element of the array,
12 – second, etc.

In my code, the array is entered by elements (after each number entering Enter).
What needs to be changed?

int input_mas (int miss_f [], int & amp; a_f)
{
COUT & LT; & LT; "Enter an array:" & lt; & lt; Endl;
    for (int i = 0; i & lt; a_f; i ++)
        While ((! (CIN & GT; & GT; (MAS_F [i])) || (cin.peek ()! = '\ n')))
        {
          cin.clear ();
          While (cin.get ()! = '\ n');
          COUT & LT; & LT; "Input error! You can only enter integers." & lt; & lt; Endl;
          COUT & LT; & LT; "Repeat input!" & lt; & lt; Endl;
        }
}

Thanks in advance.


Answer 1, Authority 100%

You see, the problem is that if you enter the entire string, then its processing will start after pressing ENTER, and somehow stupidly explain – change the fifth number, you are mistaken there … 🙂 – you have to ask you to reveal the entire line whole …

But if you go to it and the entire array is entered in one line – then you can approximately like this:

void input_mas (int miss_f [], int a_f)
{
  COUT & LT; & LT; "Enter an array:" & lt; & lt; Endl;
  BOOL FAIL = FALSE;
  for (;;)
  {
    for (int i = 0; i & lt; a_f; i ++)
    {
      if (! CIN & GT; & GT; MAS_F [i]) {fail = true; Break; }
    }
    If (Fail)
    {
      cin.clear ();
      While (cin.get ()! = '\ n');
      COUT & LT; & LT; "Input error! You can only enter integers." & lt; & lt; Endl;
      COUT & LT; & LT; "Repeat input!" & lt; & lt; Endl;
    } ELSE BREAK;
  }
}

Answer 2

Read the entire line and parser at once.

For example, with STD :: GetLine () .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions