Reputation: 21
I'm new to programming and started out with C++ just recently, learning from a book. I have a question that asks me to write a program that has 3 separate functions that:
The following is the code I wrote:
#include<iostream>
#include<array>
using namespace std;
int Fill_array(double*, int);
void Show_array(double*, int);
void Reverse_array(double*, int);
int main()
{
int temp; double val[100];
cout << "Please enter no. of values (<=100): ";
cin >> temp;
int num = Fill_array(val, temp);
int x;
cout << "Press 1 to show array & 2 to reverse array: ";
while (cin>>x)
{
if (x == 1)
{
Show_array(val, num);
cout << "Press 1 to show array & 2 to reverse array: ";
continue;
}
if (x == 2)
{
Reverse_array(val, num);
cout << "Press 1 to show array & 2 to reverse array: ";
continue;
}
else
{
break;
}
}
}
/////////////////////////////////////// function definitions
int Fill_array(double val[], int num)
{
int x = 0;
cout << "Enter values:";
while (x<num && cin>>val[x])
{
x++;
}
return x;
}
void Show_array(double val[], int num)
{
cout << "Array values: " << endl;
for (int i = 0; i < num;i++)
{
cout << val[i] << endl;
}
}
void Reverse_array(double val[], int num)
{
for (int i = 0, j = num-1; i >= j; i++, j--)
{
double temp;
temp = val[i];
val[i] = val[j];
val[j] = temp;
}
}
The function Reverse_array
doesn't reverse the order of the values in the array. Also, when I give non-numeric input during Fill_array, the program will cout<<"Press 1 to show array & 2 to reverse array: ";
but then proceeds to skip the while loop and the program just ends.
Upvotes: 0
Views: 274
Reputation: 181027
To answer the part of your question dealing with getting user input once you get input that is not a number it put cin
into an error state. You need to get rid of that error and clean out the buffer in order to get cin
back into a known good state. You can change Fill_array()
to:
int Fill_array(double val[], int num)
{
int x = 0;
cout << "Enter values:";
while (x<num && cin>>val[x])
{
x++;
}
if(!cin) // cin is in error
{
cin.clear(); // clear error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // get rid of everything in cin until you get to a newline
}
return x;
}
Upvotes: 1
Reputation: 213190
You have a simple logic error in your for
loop in Reverse_array
:
for (int i = 0, j = num-1; i >= j; i++, j--)
^^^^
This should be:
for (int i = 0, j = num-1; i < j; i++, j--)
^^^
Note that single-stepping through the code in your debugger would have shown you this mistake very quickly, so it's probably a good idea to start learning this and other basic debugging skills.
Note also that C++ already has support for many simple operations such as this - instead of "re-inventing the wheel" you could just use std::reverse
, e.g.
void Reverse_array(double val[], int num)
{
std::reverse(val, val + num);
}
Upvotes: 5