I need some help. I cant get this code to run. When I debug it tells me that the
ID: 650567 • Letter: I
Question
I need some help. I cant get this code to run. When I debug it tells me that the variable i is uninitialized. If someone could tell me how to fix this I would really appreciate it. Here is the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int pid1[4], pid2[4], pid3[4], pid4[4];
float cost[16];
char name[16][10];
int p = 0;
int ct = 0;
int n = 0;
int c = 0;
while (c != -1){
cout << "Enter sales person ID product name and product cost" << endl;
if (p % 4 == 0)
cin >> pid1[p];
else if (p % 4 == 1)
cin >> pid2[p];
else if (p % 4 == 2)
cin >> pid3[p];
else if (p % 4 == 3)
cin >> pid4[p];
cin >> cost[ct];
cin >> name[n][10];
p++; ct++; n++;
cout << "Enter -1 to quit other number to continue" << endl;
cin >> c;
}
int i;
float sum = 0.0;
cout << "Sales PersonID prodA prodb prodc prodd total";
cout << pid1[i];
for (i = 0; i<4; i++)
{
cout << " " << cost[i];
sum = sum + cost[i];
}
cout << " " << sum << " ";
cout << pid2[i];
for (i = 4; i<8; i++)
{
cout << " " << cost[i];
sum = sum + cost[i];
}
cout << " " << sum << " ";
cout << pid3[i];
for (i = 8; i<12; i++)
{
cout << " " << cost[i];
sum = sum + cost[i];
}
cout << " " << sum << " ";
cout << pid4[i];
for (i = 12; i<16; i++)
{
cout << " " << cost[i];
sum = sum + cost[i];
}
return 0;
}
Explanation / Answer
// cin >> c;
you are facing a problem -> Console is not waiting for input-from-console-when-called-multiple-times
in your case
console is not waiting for this line cin >> c; so the while loop (c != -1) never terminates.
one of the possible soultion:
I think your problem is that you need to flush the stream with a cin.ignore() at the bottom of the while loop (or else do a cin.getline() to get your input). Otherwise the newline at the end of the input (when you press enter to submit the input) gets saved for the next cin which is your cin >> c. So the newline gets used up there and doesn't actually ask the user for new input.
or
u can either break a loop after certain while loop iteration. set that one 4 in your case.
int t = 0;
while (c != -1){
if (t == 4) break;
// rest your code here.
t += 1;
}