Jump to content
xisto Community
Sign in to follow this  
kvarnerexpress

Commonly Asked C/c++ 2

Recommended Posts

How do I convert a char array to integer/double/long type?Use the atoi(), atof() or atol() functions. Also see question 1.3 below.Code:#include <stdlib.h>int main(void){ char *buf1 = "42"; char buf2[] = "69.00"; int i; double d; long l; i = atoi(buf1); l = atol(buf1); d = atof(buf2); return 0;}1.2. How do I convert an integer/float/double/long type variable to a char array?Use sprintf(). Many books/websites tell you to use itoa(), itol(), itof() etc., but these functions are compiler specific and are therefore non-portable. sprintf() is definitely the way to go.Code:#include <stdio.h>int main(void){ int i = 42; float f = 69.0; double d = 105.24; long l = 23; char buf[50]; sprintf(buf, "%d", i); sprintf(buf, "%f", f); sprintf(buf, "%f", d); sprintf(buf, "%ld", l); sprintf(buf, "%d %f %ld", i, f, l); return 0;} C++ users may also use the stringstream or ostringstream class (the deprecated form was strstream class)Code:#include <sstream>#include <string>using namespace std;int main(void) { stringstream ss; int i = 42; double d = 105.24; ss << i << " " << d; // Convert to string or char array string s = ss.str(); char buf[50]; sprintf(buf, ss.str().c_str());}1.3. How do I convert a hex/octal/any-other-base value to a number?Use strtol() or sscanf().Code:#include <stdlib.h>#include <stdio.h>int main(void){ long l; int i; unsigned int ui; char *hexstr = "12FC3"; char *octstr = "1245"; char *binarystr = "1101"; l = strtol(hexstr, NULL, 16); l = strtol(octstr, NULL, 8); l = strtol(binarystr, NULL, 2); sscanf("12", "%d", &i); sscanf("14", "%ld", &l); sscanf(hexstr, "%x", &ui); sscanf(hexstr, "%o", &ui); return 0;}C++ users may want to use stringstream instead (strstream is deprecated).Code:#include <sstream>#include <string>using namespace std;int main(void){ long l; int i; char *hexstr = "12FC3"; char *octstr = "1245"; stringstream ss; ss << hex << hexstr; ss >> l; ss.clear(); ss << oct << octstr; ss >> i; return 0;}1.4. How do I convert an integer to hexadecimal (hex) /octal (oct)?Use sprintf().Code:#include <stdio.h>int main(void){ int i = 42; char buf[50]; sprintf(buf, "%x", i); /* convert to hex */ sprintf(buf, "%o", i); /* convert to octal */ return 0;}C++ users may want to use stringstream instead (strstream is deprecated).Code:#include <sstream>#include <string>using namespace std;int main(void){ int i = 42; char buf[50]; stringstream ss; ss << hex << i; ss >> buf; ss.clear(); ss << oct << i; ss >> buf; return 0;}1.5 What's the equivalent of perl/pascal/vb/php's chr() and ord() functions in C/C++?There aren't any functions like this in C or C++ and they aren't needed anyway. You can get a char's ASCII value by simply assigning it to an integer variable.Code:char ch;int i;ch = 'A';i = ch; /* Assigns the ASCII value of 'A' (i.e.) 65 to i */printf("%d\n", i); /* Prints 65 */To do the reverse (i.e.) what the ord() function does, simply assign an integer to a char variable. You'll need to force a cast to avoid compiler warnings for some compilers thoughCode:int i;char ch;i = 65;ch = (char) i;/* some compilers don't warn you if you do:ch = i;and some will, hence the explicit cast to char type. The castassures the compilers that warn you, that you know what you're doing. */printf("%c\n", ch); /* prints 'A' */Since characters and integers are treated somewhat alike in C/C++, you can perform arithmetic operations and comparision operations with char variables, just as you do with integer variables. For instance:Code:char ConvertToUpperCase(char ch) { if (ch >= 'a' && ch <= 'z') ch = ch - 'a' + 'A'; return ch;}The above code takes a variable as input and checks if it is a lowercase letter by comparing its ASCII value to see if it is between the ASCII for 'a' and 'z'. If so, it subtracts the ASCII value of 'a' and adds the ASCII value of 'A', thereby converting it to an uppercase ASCII value.How do I print an integer/char/char array/float/double/long/long double/long long?Use appropriate formatting strings (%d, %ld, %f, %Lf, %lld) with your printf statements.Code:#include <stdio.h>int main(void){ int i = 23; long l = 42; float f = 105.23; double d = 69.05; long double ld = 55.23; long long ll = 92; char c='a'; char s[] = "This is a string"; printf("int = %d\nlong = %ld\n", i, l); printf("float = %f\ndouble = %fd\n", f, d); printf("long double = %Lf\nlong long = %lld\n", ld, ll); printf("char = "%c\nString=%s\n", c, s); return 0;}C++ users can use cout and not worry about the format string types .2.2 How do I limit the precision/length of floating point, double numbers or char strings?Use the format strings to specify precision.Code:#include <stdio.h>int main(void){ float f = 105.2345; char buf[] = "This is a string"; /* Limit to 2 decimals */ printf("float = %.2f\n", f); /* Print 10 chars wide, limit to 2 decimals */ printf("float = %10.2f\n", f); /* Print 10 chars wide, limit to 2 decimals and left-justify */ printf("float = %-10.2f\n", f); /* Limit to 10 characters */ printf("%.10s\n", buf); return 0;}C++ users may use the iomanip functions setprecision() and setw() to do this.Code:#include <iostream>#include <iomanip>using namespace std;int main(void){ float f = 105.2345; char buf[] = "This is a string"; cout.setf(ios::fixed); /* Limit to 2 decimals */ cout << setprecision(2) << f << endl; /* Print 10 chars wide, limit to 2 decimals */ cout << setw(10) << setprecision(2) << f << endl; /* Right justify to 30 chars */ cout << setw(30) << buf << endl; return 0;}2.3 How do I control how many chars are read in a string when using scanf()?You can use the a format specifier in the scanf() function.Code:char buf[25];scanf("%20s", buf);The above code limits the length of the characters that will be read by scanf() to 20 characters maximum (note that the buffer can hold 25 characters though!)C++ Users can use either setw() or cin.get()Code:cin >> setw(20) >> buf;cin.get(buf, 20);Either statement does the same thing. Note that the above code will read 19 characters max and put \0 for the 20th character.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.