c++字符串有垃圾字符

c++ string has garbage chars

本文关键字:字符 字符串 c++      更新时间:2023-10-16

我刚开始学习c++,我正在编写一个基于62的转换器程序。它适用于long-to-string函数,也适用于字符串长度小于4个字符的字符串-to-long函数。然后事情就变得奇怪了。

#include <stdio.h>
#include <math.h>
#include <string>
#include <iostream>
using namespace std;
int char_to_int(char a){
    int b=(int)a;
    if(b-(int)'0'>=0&&b-(int)'0'<10)
        return b-(int)'0';
    if(b-(int)'a'>=0&&b-(int)'a'<26)
        return b-(int)'a'+10;
    return b-(int)'A'+36;
}
char int_to_char(int a){
    if(a<10)
        return (char)(a+(int)'0');
    if(a<36)
        return (char)((a-10)+(int)'a');
    return (char)((a-36)+(int)'A');
};
long stol(string a){
    int length=a.size()-1;
    int power=0;
    long total=0;
    for(;length>=0;length--){
        total+=(char_to_int(a[length])*(long)pow(62,power));
        power++;
    }
    return total;
}
string ltos(long a){
    int digits=(int)(log(a)/log(62))+1;
    char pieces[digits];
    int power=digits-1;
    for(int i=0;i<digits;i++){
        pieces[i]=int_to_char((int)(a/pow(62,power)));
        cout<<pieces[i]<<endl;
        a=a%(long)pow(62,power);
        power--;
    }
    return string(pieces);
}
int main(){
    string secret_password="test";
    long pass_long=stol(secret_password);
    string to_out=ltos(pass_long);
    cout<<sizeof(to_out)<<endl;
    cout<<to_out<<endl;
    cout<<to_out[4]<<endl;
    cout<<to_out[5]<<endl;
    cout<<to_out[6]<<endl;
}

输出如下:

t
e
s
t
4
test═ôZAx■(
═
ô
Z

正如你所看到的,最后有一堆垃圾。我很困惑,因为我知道字符串的长度是4,但接下来的几个字符也会打印出来。我刚开始学习c++,到目前为止只使用Java,我知道c++中的字符串有一些细微差别。它可能与此有关,也可能只是与类型转换有关。

ltos中,使用string(pieces);创建字符串时,字符串类需要一个以NULL结尾的字符串:

pieces[0] = 'T';
pieces[1] = 'e';
pieces[2] = 's';
pieces[3] = 't';
pieces[4] = '';  // Same as: pieces[4] = 0;

您的数组没有尾随的0。因此,您需要告诉字符串构造函数您有多少个字符:

return string(pieces, digits);