Mayur Kharche
Mayur Kharche

Reputation: 717

Why this program skips the loop?

I can not figure out the problem with this program.

#include <iostream>

using namespace std;

int main(){

    int t;
    char s[5];

    cin>>t;
    cin>>s;

    while(t--){

       char f[100];

       cin>>f;

       cout<<f<<endl;
    }

    return 0;
}

Output:

5 abcde 
Process returned 0 (0x0)   execution time : 4.100 s
Press any key to continue.

I think it should ask for the string f five times and print the string f five times before termination.

Can anyone help me to get rid of this problem?

Thank you

Upvotes: 1

Views: 62

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Considering the terminating null-character, 5-character string is too long to fit into char s[5];. In this case, t seems happened to be just after s in the memory and your machine is using little endian, so the terminating null-character, whose value is 0, is overwritten to the least byte of t and the value of t happened to be zero.

To avoid this, you should use std::string instead of arrays of char like this:

#include <iostream>
#include <string>

using namespace std;

int main(){

    int t;
    string s;

    cin>>t;
    cin>>s;

    while(t--){

       string f;

       cin>>f;

       cout<<f<<endl;
    }

    return 0;
}

If using arrays of char is required, make the input strings short enough or increase buffer size to enable it store all possible input without causing buffer overrun.

Upvotes: 3

Related Questions