0

I have a c++ code below that takes a string as input and outputs it n times. The while loop is functioning one less than expected: For eg if I input n=1, the loop does not function
For n=2, the loop functions 1 time and so on:
Can anyone explain the error in logic.

int main(){
    int n;
    string line;
    cin>>n;
    while(n){
        getline(cin,line);
        cout<<line<<"\n";
        n--;
    }
}

Thanks in advance

  • 5
    Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Paul R Sep 12 '16 at 07:03
  • 1
    If learning about how to use a debugger is not what you want at the moment, you can also use 'printf-debugging' by adding output e.g. the values of the condition and the result of the condition. – MrSmith42 Sep 12 '16 at 07:18

0 Answers0