For loop not executing as desired

I'm making a simple program on C++ that reads numbers and outputs said number in english text. It can read numbers from 0 to 9,999,999. I divided it into functions, a function for the ones, a function for the tens, hundreds, thousands and millions.

I have a for loop in the millions function that passes only some digits from the entire number to another string, but it is only executing once and it is not copying the digits:

`

string millionths(string num_i)
{
    string num_m;
    string num_l;
    string num_ln="000000";
    string num_ln5="00000";
    string num_ln4="0000";
    string num_ln3="000";
    string num_ln2="00";
    int it;
/*I just want the last 6 characters from num_i to be copied to num_ln
but the loop is only executing once and doesn't copy any value*/
    for(it=0;it<6;it++);
        {num_ln[it]=num_i[it+1];}
    num_m=units(num_i[0]);
    if(num_ln=="000000")
        return num_m+" million";
    else if(num_ln[0]=='0'&&num_ln[1]=='0'&&num_ln[2]=='0'&&num_ln[3]=='0'&&num_ln[4]=='0')
    {num_l=units(num_ln[5]);}
    else if(num_ln[0]=='0'&&num_ln[1]=='0'&&num_ln[2]=='0'&&num_ln[3]=='0')
    {for(it=0;it<2;it++);
        {num_ln2[it]=num_i[it+5];}
    num_l=tenths(num_ln2);}
    else if(num_ln[0]=='0'&&num_ln[1]=='0'&&num_ln[2]=='0')
    {for(it=0;it<3;it++);
        {num_ln3[it]=num_i[it+4];}
    num_l=hundreths(num_ln3);}
    else if(num_ln[0]=='0'&&num_ln[1]=='0')
    {for(it=0;it<4;it++);
        {num_ln4[it]=num_i[it+3];}
    num_l=thousanths(num_ln4, 1);}
    else if(num_ln[0]=='0')
    {for(it=0;it<5;it++);
        {num_ln5[it]=num_i[it+2];}
    num_l=thousanths(num_ln5, 2);}
    else
    {num_l=thousanths(num_ln, 3);}
    return num_m+" million "+num_l;
}

`

I really appreciate your help.

Upvotes: 1

Views: 63

Answers (1)

shuttle87
shuttle87

Reputation: 15934

This is an empty for loop on the first line here:

for(it=0;it<6;it++);     //You don't want to do this
    {num_ln[it]=num_i[it+1];}

The result is that this loop runs without actually doing anything and finishes with it == 6. The result is that num_ln[it]=num_i[it+1] is only done once and only done with it=6. This is probably not what you want as it only copies one element across. This can be fixed as follows:

for(it=0;it<6;it++){
    num_ln[it]=num_i[it+1];
}

By using a more standard brace style this problem is resolved, it will also make it much much easier for other programmers to read and understand your code.

Upvotes: 1

Related Questions