Generating next binary bit from given binary string

I've got this assignment:
First line is the number of test (t)
Following lines are the binary strings (a)
Print out the result each on individual line
The condition
1<=t<=100
1<=length(a)<=1000
example:
Input:
2
010101
111111
Output:
010110
000000
Here's my code, the auto grader kept on telling me I got my answer wrong but I can't figure out where I got it wrong
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream> 
#include<string>
using namespace std;
string a;
int t;
string next(){
    int i=0;
    for(i= a.length() - 1; i >= 0; i--){
        if(a.at(i) == '0'){
            a.at(i)='1';
            break;
        }
        else {
            a.at(i) = '0';
        }
    }
    /*if(i<0 && a.length()<=999)
        a='1'+a;*/
    return a;
}
int main(){
    bool ck;
    do{
        ck = true;
        cin >> t;
        if(t<0 || t>100)
             ck = false;
    }
    while(ck==false);
    //cin >> t;
    while( t >= 0 ) {
        getline(cin, a);
        if(a.length() > 0 && a.length()<=1000){
            cout << next() << endl;
        }
        t--;
    }
    return 0;
}
Last edited on
Stop changing your code - it makes it difficult to reply to you.

You are mixing stream extraction >> with getline. The first leaves the '\n' character in the stream and the latter then picks up the remaining empty line.

Change your line
cin >> t;
to
cin >> t; cin.ignore( 1000, '\n' );
which will clear the newline.


Then you can put your line
while( t >= 0 ) {

back to the more sensible
while( t > 0 ) {


Whilst it would then appear to work there are a lot of issues with your code. Didn't your mother tell you not to pick up unnecessary global variables? - you don't know where they've been! Also, rather than setting booleans like ck to "true" or "false" you can set them directly to the result of a test.
Last edited on
Thank you
I changed the while condition because for some reason it only run for n-1 times with my original code
For example if I put in 3 it will only run 2 times. Maybe because I didn't clear newline as you said
Topic archived. No new replies allowed.