Home > OS >  Issue with str.push_back
Issue with str.push_back

Time:03-29

I am trying to create a C function with the following behavior:
Input: "A4B5C3" ; Output: "AAAABBBBBCCC"
Input: "R1T3" ; Output: "RTTT"
And so on.

I have written the following function:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string foo(string s){
    int count = 0;
    string t = "";
    char letter = 'a';

    for (string::iterator it=s.begin(); it<s.end(); it  ){
        if(count%2==0)
        {
            cout << "count: "<<count << " *it: "<< *it << endl;
            letter = *it;
        }
        else
        {
            cout <<"count: "<< count << " *it: " << *it << " letter: " << letter << endl;
            int j = 0;
            while (j<*it)
            {
                t.push_back(letter);
                j  ;
            }
        }
        count  ;
    }
    cout << endl<<endl;
    return(t);
}

However , on calling foo("A1B4C2D8"), I get this output:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
For some reason, my while loop seems to be running 48 more times than I would like it to...

CodePudding user response:

There are no character encodings where the integer 1 is equal to the character '1' (for example).

In the ASCII encoding the character '1' is equal to the integer 49.

That means the condition j<*it is flawed.

The C specification requires that all digits are encoded consecutively, so '0' will always come before '1', and '1' will always come before '2', and so on. With that knowledge, together with knowing that char is a simple integer type, you can always subtract '0' from any digit character to get its integer value.

For example '2' - '0' == 2.

To solve your problem the condition should be j < (*it - '0').

CodePudding user response:

Here :

  while (j< *it)

you are comparing an integer (int) with a character (char). The character '0' does not equal 0, but as digits have consecutive representations you can subtract '0' from the character to get the corresponding integer:

  while (j< *it - '0')

CodePudding user response:

Issue is in the line

int j = 0;
while (j<*it)

... You are comparing the int value with the chacter.

CodePudding user response:

The character '0' in ASCII encoding has the hexadecimal integer value 0x30 and the decimal integer value 48. The character '1' has the hexadecimal integer value 0x31 and the decimal integer value 49. And so on till '9' that has the hexadecimal integer value 0x39 and the decimal integer value 57.

Even not knowing those ASCII codes the shortest fix is changing int j = 0; to

int j = '0';

or char j = '0';. Then the loop while (j < *it) will iterate correctly.

  •  Tags:  
  • c
  • Related