|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
Commonly Asked C/C++ Questions
Here are some answers to commonly asked C/C++ questions on the forum. If you are new to the forum, please read this thread as your question may already be answered here. This guide is divided into many sections:
0. Frequently Asked Newbie Questions (how do I pause output, compile my program etc.) 1. Converting types 2. Formatting Output 3. String manipulation (copy, concatenate, replace etc.) 4. File Manipulation (File size, dir contents, remove files etc.) 5. Secure Programming Practices for Newbies. This guide is a work in progress, so feel free to PM me with your suggestions. CREDITS --------------- (in order of how they replied to the original thread) DaWei_M Deltron74 grumpy movEAX_444 mitakeet NetBSD User Name infamous41md
__________________
Up the Irons What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home. "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest Down with Sharon Osbourne Puzzle of the Month solved by Keath and KevinADC, superior perl programmers of the month Looking for a perl job with kick-*** programmers in a well-known NASDAQ listed tech company with branches in the US and Europe? We're hiring. PM me for details. Requirements Last edited by Scorpions4ever : September 28th, 2004 at 07:43 PM. |
|
#2
|
||||
|
||||
|
0. Frequently Asked Newbie Questions (FNGFAQ)
0. Frequently Asked Newbie Questions (FNGFAQ)
---------------------------------------------- 0.1. Where can I get a C or C++ compiler? Depends on your operating system. See the following links: http://www.compilers.net/Dir/Free/Compilers/CCpp.htm http://www.bloodshed.net/compilers/index.html http://www.openwatcom.org/ (Formerly Watcom/Sybase compiler) http://www.digitalmars.com/ (Formerly Symantec/Zortech compiler) http://community.borland.com/museum/ (Ancient Borland compilers) http://msdn.microsoft.com/visualc/vctoolkit2003/ (Free Visual C++ 2003 Toolkit) http://www.borland.com/products/dow...d_cbuilder.html (Borland C++ Builder Trial Version download) In general, people on this forum generally use the following: On Unix-like OS (Linux, FreeBSD, OpenBSD, NetBSD, Darwin etc.): gcc tendra (this is a relatively unknown compiler though ).On Windows: Bloodshed Dev C++ (which uses gcc as the backend) Visual C++ Borland C++ and Borland C++ Builder 0.2 How do I compile my program? On unix-like systems: gcc -o exename myfile.c This will compile myfile.c to produce an executable file called exename. You can then run exename by typing ./exename On Windows systems, different compilers have different keys to compile a program. Bloodshed/Dev C++: Ctrl-F9 compiles, Ctrl-F10 executes. Visual C++: F7 compiles, F5 executes. Borland C++ Builder: Ctrl-F9 compiles, F9 executes. Turbo-C: F9 compiles, Ctrl-F9 executes. 0.3 I cannot see my C compiler output. The window is closing too quickly for me. This is a common question that many newbie programmers on Windows have. See http://forums.devshed.com/t157960/s.html for many solutions. 0.4 What are some handy C/C++ links? http://www.eskimo.com/~scs/C-faq/top.html http://www.parashift.com/c++-faq-lite/ 0.5 Why does my scanf/fscanf/sscanf stop working? Most C input is provided in a stream. That is, it is a series of characters made available one at a time. The scanf() function family are format-sensitive functions; they not only collect the characters for you, but attempt to convert them to a type (such as an integer) that you specify. They have great difficulty converting ZyGH4 to a meaningful number so they fail. The conversion attempt is governed by format specifiers that YOU provide. Since these may not match the input actually encountered, the family returns a value indicating the number of items successfully scanned AND assigned. If this value is zero, you have nothing. If this value is EOF, there was an end-of-file or other error. If you don't examine the return, how will you know? If an error occurs it will not be automatically cleared. Operations on the stream will continue to return an error until clearerr(), fseek(), fsetpos(), or rewind() is called. This means that a loop that is designed to pause for input will loop indefinitely. The characters that f/s/scanf attempt to convert as one value are all the characters up to the first whitespace character (space, tab, newline) or up to the specified field width, or up to the first character that cannot be converted. (Note: The [ and c format directives are not whitespace delimited, but we won't consider them for the explanation here). If a character conflicts with the format specification, the function terminates and the character is left in the stream as if it had not been read. You probably will not expect it to be there to serve as input for your next call, so your input will not behave as you expect. Example of proper usage: int status; status = scanf ("%s%d\n", name, &number); Check the value of 'status' after the scanf() call. If it is not what you expect (two, in this case), you didn't get all your fields. If it is EOF, your stream is broken and will remain so until you clear the error. 0.6 Why does getline() not work correctly with Visual C++ (VC++)? Why do I have to type Enter twice for getline to process my input line? If you're reading this, you've probably noticed that getline() is not functioning the way your book says it should -- you need to hit <enter> twice for the program to read your input. For example: Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout<<"Enter a name:\n";
getline(cin, name);
cout<<name<<endl;
return 0;
}
This is because there's a known bug in Visual C++'s implementation of getline() (in the VC++ 6.0 Standard/Professional/Enterprise editions only, .NET has the fix). See the fix here: http://support.microsoft.com/defaul...B;EN-US;q240015 Further reading: http://forums.devshed.com/showthread.php?threadid=51971 Last edited by Scorpions4ever : December 9th, 2004 at 10:26 AM. |
|
#3
|
||||
|
||||
|
1. FACQ - Frequently Asked Conversion Questions
1. FACQ - Frequently Asked Conversion Questions
===================================== 1.1 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 though Code:
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 cast
assures 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. Last edited by Scorpions4ever : November 13th, 2004 at 11:25 AM. |
|
#4
|
||||
|
||||
|
2. Frequently Asked Print Formatting Questions
2. FREQUENTLY ASKED PRINT FORMATTING QUESTIONS
========================================== 2.1 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. 2.4 How do I print a triangle, hourglass, sinewave or upside-down triangle? See this thread: http://forums.devshed.com/t137892/s.html and search this forum for more examples. Last edited by Scorpions4ever : November 20th, 2004 at 09:46 AM. |
|
#5
|
||||
|
||||
|
Place holder for Chapter 3.
|
|
#6
|
||||
|
||||
|
Place holder for Chapter 4.
|
|
#7
|
||||
|
||||
|
5. Secure Programming Practices for Newbies
-------------------------------------------- Here's a FAQ put together by our very own mitakeet, with feedback from infamous41md. It covers several security issues, not just with C/C++ programming, but general practices to ensure the security of your applications. This article is a work in progress, so check back often: http://sol-biotech.com/code/SecProgFAQ.html |
|
#8
|
||||
|
||||
|
I created a bit of a tutorial on performance programming at http://sol-biotech.com/code/PerformanceProgramming.html in case someone is interested.
__________________
Left DevShed May 28, 2005. Reason: Unresponsive administrators. Free code: http://sol-biotech.com/code/. Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html. Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html. It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it. --Me, I just made it up The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man. --George Bernard Shaw |
|
#9
|
||||
|
||||
|
These are some FAQ's that I have posted a billion times:
Programming with multiple processes and Inter-Process Communication Programming Sockets (Unix based, but concepts transcend platforms) Windows Specific Socket Issues: Winsock Packet Sniffing and Injecting: Raw Sockets The Art of Unix Programming: Everything you need to know about *nix THe Unix Programming FAQ: If it's not in the one above, it's probably here Gettting strange SEGFAULTS when allocating or freeing memory? Posix Threads: Multithreading On *nix Advanced POSIX thread issues So you want to be a h4x0r? Start checking out some of these articles, and of course, all the links found in my sig
__________________
|