c++ - Interesting mistake in string pointer -
i created function transforms number equivalent in given base , prints string. looks flawless gives absurd results. code below should translate 100 base 9 , give "121".
#include <iostream> #include <fstream> #include <string> using namespace std; void doldur(string *s,int u,int base){ *s=""; while(u!=0){ *s=""+u%base+*s; u/=base; } return; } int main() { ofstream fout ("dualpal.out"); ifstream fin ("dualpal.in"); int i; string hey; doldur(&hey,100,9); cout<<hey; cin>>i; return 0; }
but ridiculously, prints dualpal.outualpal.outdualpal.out.(also gives other interesting results different bases)
where's flaw?
you're incrementing pointer empty string u%base
places , using construct std::string
, looks null terminator. causes undefined behaviour. use std::string
off bat:
*s = std::string() + ...;
next, there's no conversion int
std::string
. use function std::to_string
:
*s = std::to_string(u%base) + *s;
the first operand pointless, removed it. finally, of dereferencing bit tiresome, no? i'd make 1 , return it:
std::string doldur(const std::string &s,int u,int base){ std:string ret; while(u!=0){ ret = std::to_string(u%base) + ret; u/=base; } return ret; }
don't worry performance loss returning. or use reference , change original if prefer:
void doldur(std::string &s,int u,int) { s.clear(); while(u!=0){ s = std::to_string(u%base) + s; u/=base; } }
Comments
Post a Comment