My program is supposed to stop the user from inputting a duplicate time for a ru
ID: 3778565 • Letter: M
Question
My program is supposed to stop the user from inputting a duplicate time for a runner. My input validation (while loop) is still allowing duplicate times to be put in, what am i doing wrong?
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
main()
{
char name[3][10];
int time[3];
for(int i = 0; i < 3; i++)
{
cout << "What is runner number" << " " << i+1 << "'s name?"<< endl;
cin >> name[i+1];
}
for(int i = 0; i < 3; i++)
{
cout << "What was" << " " << name[i+1] << "time?(in seconds)" << endl;
cin >> time[i];
while(time[i+2] == time[i] || time[i+1] == time[i] || time[i+1] == time[i+2]) // this validation is not working.
{
cout << "Sorry you cant enter a duplicate time" << endl;
cin >> time[i];
}
}
ofstream writer("runner.dat");
cout << "Name" << setw(7) << "Time" << endl;
for(int w = 0; w < 3; w++)
{
cout << name[w+1] << setw(7) << " " << time[w] << endl;
}
for(int l = 0; l < 3; l++)
{
writer << name[l+1] << setw(7) << " " << time[l] << endl;
}
writer.close();
}
Explanation / Answer
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char name[3][10];
int i,w,l, time[3];
for(i = 0; i < 3; i++)
{
cout << "What is runner number" << " " << i+1 << "'s name?"<< endl;
cin >> name[i+1];
}
for(i = 0; i < 3; i++)
{
cout << "What was" << " " << name[i+1] << " time?(in seconds)" << endl;
cin >> time[i];
//in this code you have check with next element you cant read data from user then it returns null so it no working properly.
//For example i = 0 you have read the value from user and store in time[0] but you cant read remining data, but you check with those also. so the condition not working properly
//while(time[i+2] == time[i] || time[i+1] == time[i] || time[i+1] == time[i+2]) // this validation is not working.
//{
// cout << "Sorry you cant enter a duplicate time" << endl;
// cin >> time[i];
//}
if(i==1)
{
while(time[i-1] == time[i]){
cout << "Sorry you cant enter a duplicate time" << endl;
cin >> time[i];
}
}
else if(i == 2){
while(time[i-1] == time[i] || time[i-2] == time[i]){
cout << "Sorry you cant enter a duplicate time" << endl;
cin >> time[i];
}
}
}
ofstream writer("runner.dat");
cout << "Name" << setw(7) << "Time" << endl;
for(w = 0; w < 3; w++)
{
cout << name[w+1] << setw(7) << " " << time[w] << endl;
}
for(l = 0; l < 3; l++)
{
writer << name[l+1] << setw(7) << " " << time[l] << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.