#include <iostream>
using namespace std;
int fill_array(double ar[], int limit);
int main()
{
double ar[7] = {0};
fill_array(ar, 7);
system("PAUSE");
return 0;
}
int fill_array(double ar[], int limit)
{
double temp;
for (int i = 0; i < limit; i++)
{
cout << "Give number " << i + 1 << ": ";
cin >> temp;
ar = temp;
cout << ar;
}
return i;
}
It fills whole array with the number last given but I don´t really understand why, so plz help.
character value
What happends when I give character rather than double value when asked?
could it be that the loop just goes too fast?
maybe you should do a small sleep between every cycle.
maybe it just runs all the loop while you still have
your finger on the key.
(just a guess)
maybe you should do a small sleep between every cycle.
maybe it just runs all the loop while you still have
your finger on the key.
(just a guess)
Try replacing cin >> temp with this:
if cin can't store the input it "fails" and the input buffer needs to be cleared. In the failed state cin will not except any new input.
while(!(cin >> temp)){cin.clear();while(cin.get() != '\n'){}}
if cin can't store the input it "fails" and the input buffer needs to be cleared. In the failed state cin will not except any new input.
Standard input requires a newline after your input, so the loop can't go to fast.
But that newline is the problem, it's still in the inputstream, after reading the number and that sets the stream in "bad"-mode, when it tries in the next iteration to read a new number.
To avoid this you have to clear the stream for the next value.
Try this (I hope it works):
But that newline is the problem, it's still in the inputstream, after reading the number and that sets the stream in "bad"-mode, when it tries in the next iteration to read a new number.
To avoid this you have to clear the stream for the next value.
Try this (I hope it works):
#include <iostream>using namespace std;int fill_array(double ar[], int limit);int main(){ double ar[7] = {0}; fill_array(ar, 7); system("PAUSE"); return 0;}int fill_array(double ar[], int limit){ double temp; for (int i = 0; i < limit; i++) { cout << "Give number " << i + 1 << ": "; cin >> temp; cin.ignore( ); ar = temp; cout << ar; } return 1; // i exists only in the for loop-scope}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement