c++字符串有垃圾字符
c++ string has garbage chars
我刚开始学习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);
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数