Reputation: 11
I'm trying to write a program that translates input into its binary form using C++. However i'm having a bit of problem with the do-while loop portion that continues to translate each additional input. The condition for the do-while loop is messed up so the output becomes an infinite loop.
do{
cin>>number;
if (number<0)
cout<< number<< " (base 10) is not a positive integer"<<endl;
else if (number==0)
cout<< number<< " (base 10) = 0 (base 2) ";
else {
binary= binaryConverter(number);
cout<< number << " (base 10) =";
cout<< binary << " (base 2)";
}
cout<< endl;
}while(????);
Upvotes: 1
Views: 5397
Reputation: 168876
The canonical C++ input loop looks like this:
ItemType item;
while ( input_stream >> item ) {
// Do something with item, for example:
// std::cout << item; or,
// container.push_back(item); or,
// sum += item; or whatever.
}
That sort of loop will run exactly once per input item, will stop at end-of-file (whether it is the end of a disk file or EOF signaled from the console). It will also stop as soon as the input no longer comports to the format of an item (for example, if ItemType
is int
and the input has the letter Q in it.)
Specifically, one should never use .eof()
or .good()
as a loop condition. One should hardly ever use a do-while
as the input loop.
In your case, the loop should look like:
while(std::cin >> number) {
std::cin>>number;
if (number<0)
std::cout<< number<< " (base 10) is not a positive integer";
else if (number==0)
std::cout<< number<< " (base 10) = 0 (base 2) ";
else {
binary= binaryConverter(number);
std::cout<< number << " (base 10) =";
std::cout<< binary << " (base 2)";
}
std::cout<< "\n";
}
P.s. I modified your code to conform to two other widely-adopted standards: never say using namespace std;
and never say std::endl
when you mean '\n'
.
Upvotes: 0
Reputation: 454
This will loop till termination signal is received (like CTRL-C), then stream is terminated
while(cin >> number)
Upvotes: 3