2014-04-29 4 views
0

저는 C++에 들어가기 시작했고베이스 62 변환기 프로그램에서 작업하고있었습니다. 문자열이 4 자 이하로 길면 long 함수에서 long 함수로 잘 작동합니다. 그러면 사물이 이상해진다. 다음과 같이C++ 문자열에 쓰레기 문자가 있습니다

#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에서

+0

문자열을 종료하는 것이 확실합니까? –

+0

@ JohnnyMopp 제안을 주셔서 감사합니다. 현재 더 잘 작동합니다. 암호 = "1000"일 때 하나의 버그가 발생했습니다. [00. 또한 더 큰 숫자로 작업하기 위해 이것을 확장하고 싶습니다. 거기에 C++에서 오래보다 큰 데이터 형식이 있나요? –

+0

대부분의 시스템에서 long과 int는 모두 4 바이트입니다. long long은 8 바이트입니다. –

답변

1

당신이 string(pieces); 문자열을 생성, 문자열 클래스는 NULL 문자열을 종료 기대 :

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

귀하의 배열은 0 후행 그래서 어떻게 문자열 생성자를 말할 필요가 없습니다 많은 문자 :

return string(pieces, digits); 
관련 문제