Post date: Jan 24, 2014 7:17:51 AM
1 1
1 11
0 011
1 0111
0 00111
0 000111
0 0000111
i.e if user types 1 then 1 will be at printed right shift, and 0 will be printed left shift.
Note: There is no definite count of number of Inputs user wants to give, or sequence of inputs user wants to give.User can give any number of inputs, and it should display the result as above.
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Print number in specified format.
Created Date : 20-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
void Help()
{
cout << "Please input 0 for left shift \n"
" 1 for right shift \n"
" 2 for quit \n" << endl;
}
int main()
{
int zeros(0);
int ones(0);
int in;
Help();
while (true){
cin >> in;
if (cin.fail())
{
cout << "invalid input" << endl;
Help();
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n' );
continue;
}
if (in == 0){
zeros++;
}
else if (in == 1){
ones++;
}
else if (in == 2){
break;
}
else{
cout << "Invalid input" << endl;
Help();
continue;
}
cout << setw(4) << left << in;
for (int i = 0; i < zeros; i++){
cout << 0;
}
for (int i = 0; i < ones; i++){
cout << 1;
}
cout << endl;
}
return 0;
}
Output
Please input 0 for left shift
1 for right shift
2 for quit
0
0 0
1
1 01
1
1 011
01
1 0111
11
Invalid input
Please input 0 for left shift
1 for right shift
2 for quit
1
1 01111
1
1 011111
q
invalid input
Please input 0 for left shift
1 for right shift
2 for quit
2
Press any key to continue . . .
Question
You need to write this program again, without using any library methods.Take the following inputs from user and print the following output.
If cin fails, you have to clear error state, otherwise the loop will never end.