for (int i = 0; i < 5; i++)
{
// do stuff with ara[i]
// e.g.
ara[i] = 42 + i;
}
convert the data that I need using atof
Since you're dealing with integers, you can use atoi instead. (Or, stoi in C++11, which can handle '0' values)
So... first, get input:
1 2
string input;
cin >> input;
Then convert that input to an int: int n = atoi(input.c_str());
(The "c_str()" converts the string to a format that is recognizable by C library functions like atoi)
Then use that n and store it in the appropriate spot.
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
int main()
{
int arr[5]{};
for (int i = 0; i < 5; i++)
{
std::cout << " Enter #" << i + 1 << ": ";
std::string input;
std::cin >> input;
try
{
arr[i] = stoi(input);
}
catch (const std::exception& exc)
{
std::cout << "\n " << exc.what() << "\n\n";
i--;
}
}
// <--- Keeps console window open when running in debug mode on Visual Studio.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
Enter "a123" and see what happens.
I rearranged your prompt a little. It makes more sense to a user.