Stop using the atoi() function! Yes, it’s a golden oldie, often my go-to function for converting strings to integers, but it’s weak. The strtol() function, on the other hand, not only converts strings to integers, it can validate input as well.
Continue reading
Author Archives: dgookin
Write Your Own Integer Conversion – Solution
This month’s Exercise is to emulate the antique atoi() function, which converts a string of digits into an integer value.
Continue reading
Peculiarities of the strtol() Function
Imagine my disappointment to learn that the atoi() function, one of the first I learned in C, is actually a macro. I’m horrified. As much as I treasure converting strings to integers, I shall survive this life-changing discovery.
Continue reading
Write Your Own Integer Conversion
It’s not that programmers are lazy. Many professions involve a lot of copy-and-paste, borrowing stuff done before, re-purposing and re-using. Why re-invent the wheel? Still, doing so helps exercise your programming kung-fu as well as offers insights into how things work and why some operations are done the way they are.
As an example, consider the atoi() function.
Continue reading
Exponentiation
The C language lacks an exponentiation operator, which would raise a base value to a certain power. For example: 2^8, which in some programming languages is an expression to raise 2 to the 8th power. Instead, C uses the pow() function.
Continue reading
The Perils of strncpy()
Always be careful when manipulating strings! Tack on that null character, '\0', at the end of a string! And don’t worry about the C language string functions: They perform this important feature for you. But do they all?
Continue reading
To Read a Chunk a Data
Say you must read 2048 bytes from a file. Which of the following fread() statements works for you: A, B, both, or neither?
A. c = fread( buffer, 2048, 1, fh);
B. c = fread( buffer, 1, 2048, fh);
Continue reading
Old Habits Die Hard
Like doing anything for a long period of time, I find myself often using the same approach to solving a programming puzzle. It’s habit. It’s tradition. And it often hinders my insight into the language.
Continue reading
Parse and Count Words in a String – Solution
The key to making this month’s Exercise work isn’t to know when a word stops, but when the separator characters stop. That’s because words aren’t always separated by single characters.
Continue reading
Parse and Count Words in a String
This month’s Exercise is based on code presented in the June 1 Lesson: split a string into separate words. The difference is that each word you pluck from the string is followed by the number of letters in that word.
Continue reading