answersLogoWhite

0

#include<iostream>

int main()

{

int n[4];

std::cout << "Enter 4 integers: "

std::cin >> n[0] >> n[1] >> n[2] >> n[3];

}

The above is naive because there's no error-checking to prevent garbage input. A better solution is to input 4 strings and then convert those strings to integers. If the conversion fails, simply ask for new input until the conversion succeeds. The following shows one method of achieving this:

#include<iostream>

#include<sstream>

int main()

{

int n[4];

// repeat until valid

bool valid {false};

while (!valid)

{

// create 4 temporary strings for input

std::string s[4];

std::cout << "Enter 4 integers: "

std::cin >> s[0] >> s[1] >> s[2] >> s[3];

// assume input is valid until proven otherwise

valid = true;

for (size_t i=0; valid && i<4; ++i)

{

// convert the current string to an integer

std::stringstream ss {s[i]};

valid = (ss >> n[i]);

}

}

// When we reach here, n[] will contain 4 valid integers.

// Use n[] ...

}

User Avatar

Wiki User

10y ago

What else can I help you with?

Continue Learning about Engineering