sentinel controlled while loop.
need to read numbers from an input file until i read a certain number say 1234.
then output the total count of the numbers that have been processed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
constint SENTINEL = 99999;
int main(void)
{
int numbers;
int totalCount;
numbers = 0;
inFile >> numbers;
while (numbers!=SENTINEL)
totalCount+= numbers;
inFile >> numbers;
# include <iostream>
# include <fstream>
usingnamespace std;
int main()
{
ifstream inFile("file.txt");
int HOW_MANY_NUMBER_I_WANT_TO_READ = 0;
cout << "How many numbers you want to read -> ";
cin >> HOW_MANY_NUMBER_I_WANT_TO_READ;
int number = 0;
int totalCount = 0;
for(int i=0;i<HOW_MANY_NUMBER_I_WANT_TO_READ;i++)
{
inFile >> number;
totalCount += number;
cout << "The number " << i+1 << " is : " << number << endl;
cout << "The total count is : " << totalCount << endl << endl;
}
return 0;
}
Techno01's example does not use a sentinel, probably not a good idea to use that code.
Your program is missing brackets, should work though. I assume you haven't posted all of the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
constint SENTINEL = 99999;
int main(void)
{
/* ... */
int totalCount = 0;
int numbers;
inFile >> numbers;
while (numbers!=SENTINEL) // hope the sentinel is in the file!!!
{
totalCount+= numbers;
inFile >> numbers;
}
/* ... */
}
Maybe you're half right @LowestOne .I thought that he want to get 1234 number from the file wich is SENTINEL.
Now I think he want to get total counts of numbers until he find SENTINEL am I right?
If that the case my code will be suggested like this:
# include <iostream>
# include <fstream>
usingnamespace std;
int main()
{
ifstream inFile("file.txt");
constint SENTINEL = 21;
int numbers;
int totalCount;
numbers = 0;
totalCount = 0;// must initialised too because It takes a random value and will be countd
// inFile >> numbers; no need for this one
//if we get numbers = SENTINEL we wont get any totalCount
while (numbers!=SENTINEL)
{
inFile >> numbers;
totalCount+= numbers;
}
cout << "Total count = " << totalCount << endl;
return 0;
}