0

So the problem is, that this code:

string num = "00101011110011100001";
string quartett;
int i = num.length() - 1;
while (i > 0) {
    quartett.clear();
    quartett = num.substr((i - 3), i);
    cout << quartett << endl;
    i = i - 4;
}

Prints out this:

0001
11100001
11001110000
1011110
001

actual output should be:

0001
1110
1100
1011
0010

The thing is I don't have any idea why. I hope you can help me and thanks in advance.

1
  • 2
    Since you're assigning to quartett with the substring() call, the clear() is pointless. It cannot be the reason for the problem. Commented Apr 10, 2014 at 10:20

4 Answers 4

6

The second argument to substr() is length, not index. Should be:

quartett = num.substr((i - 3), 4);
Sign up to request clarification or add additional context in comments.

Comments

4

The second parameter in substr is the number of characters you want to print. As you've set that to i, the amount of characters outputted will grow on each iteration.

I think you want to hardcode that to 4.

By the way, your call to quartett.clear(); is pointless as you're assigning it in the following statement.

1 Comment

Thanks alot. i've been mistaking that with another language :S
0

The substr method

basic_string substr( size_type pos = 0,
                     size_type count = npos ) const;

takes second parameter as number of characters you want to extract. If this is omitted then the meaning is "to the end of string". Consider example:

std::string a = "0123456789abcdefghij";

std::string sub1 = a.substr(10);
std::cout << sub1 << '\n';

std::string sub2 = a.substr(5, 3);
std::cout << sub2 << '\n';

output:

abcdefghij

567


Thus what you need is quartett = num.substr((i - 3), 4);

http://en.cppreference.com/w/cpp/string/basic_string/substr

Comments

0

use this:

string num = "00101011110011100001";
string quartett;
int no = 4;
int i = num.length();
while (i > 0) {
    quartett.clear();
    quartett = num.substr((i - no), no);
    cout << quartett << endl;
    i = i - no;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.