简体   繁体   中英

C++ string.clear() doesn't empty my string

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.

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

quartett = num.substr((i - 3), 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.

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM