Conversion Between String and Number

◀ Pause For Some Time▶ Tokenize a String
Amazon The header <stdlib.h> provides the following functions for number conversion:
  • double atof(const char *s): converts s to double
  • int atoi(const char *s): converts s to int
  • long atol(const char *s): converts s to long
Note that all the above functions have the common property that if the given string contains characters other than numbers, they still return some value; they don’t crash. They also work with negative values. Conversions to string from double, int, and long may need to be written by you.

The following function, dtoa(), converts a double or int to a string. It also works with negative values.
int getnod(int a){
	int t=1;
	while((a/=10)!=0)
		t++;
	return t;
}
bool allZeros(string s){
	for(int i=0; i<s.length(); i++)
		if(s[i]!='0')
			return false;
	return true;
}
string dtoa(double val){
	char *buffer;
	string bufs;
	int precision = 6;
	int decimal, sign, i;
buffer = fcvt(val, precision, &decimal, &sign); bufs+=buffer; if(decimal<=0){ bufs.insert(0,"0."); for(i=0;i>decimal;i--) bufs.insert(2,"0"); } else{ if(allZeros(bufs.substr(getnod((int)val)))) bufs=bufs.substr(0,getnod((int)val)); else bufs.insert(getnod((int)val),"."); } if(sign==0) return bufs; return "-"+bufs; }
◀ Pause For Some Time▶ Tokenize a String

fShare
Questions? Let me know!