April 3rd, 2013, 05:24 PM
How does strcspn work?
Trying to get the basics of file writing and parsing in C.
I am trying to understand exactly how strcspn works when it comes to removing the new line. Does anyone know of a good link or can explain in simple terms how this works?
I also have another questions about this bit of code from a larger program I am looking at. This bit prints the line just stored into the lineBuffer array. But what's with all the backslashes?
printf ( "Line read = \"%s\"\n", lineBuffer ) ;
Sorry if I didn't explain this well. Please feel free to go in depth or ask more more questions about the problem.
April 3rd, 2013, 05:34 PM
The back slashes are "Escape" characters. They allow you to print the special characters like the quotation mark "\"", the backslash character "\\", or the new line character "\n".
April 3rd, 2013, 05:36 PM
Thank you for your help. So would the line print out with the quotation marks?
Originally Posted by jimblumberg
April 3rd, 2013, 05:58 PM
I've never used strcspn, but a man page for it is at http://linux.die.net/man/3/strcspn
As said, back slashes are used for escaping characters in C strings and in UNIX shells. That is to say that it indicates that the following character is to be used in an alternative manner.
If you tried to place a double quote inside a string, the compiler would misinterpret that as marking the end of the string, so you need to escape it (ie, "\"") for it to appear as a normal character in the string. Same for a percent sign, which normally marks where printf will insert a value, so if you want to display a percent sign you'd have to escape it (eg, "Percentage: %5.2f \%"). And for the backslash itself as well in order to show that it's not being used for escaping (eg, "C:\\Program Files\\Adobe").
But wait, there's more! 'n' is just the letter n, but '\n' is a newline character. Similarly, '\t' is tab, '\r' is carriage return, '\a' is bell, '\b' is backspace, '\f' is form feed.
If you escape a number, that that's the ASCII code of the character, though that number has to be in octal (AKA "base 8"). So '\0' is the null-terminator (byte of zero that marks the end of a C-style string -- most highly important character), '\7' is bell, '\40' is space (32 decimal). You can also enter ASCII codes in hexadecimal by adding a 'x'; eg, '\x0a' is linefeed, '\x0d' is carriage return, '\x20' is space (32 decimal, 040 octal). Needless to say, I very much prefer hex, which I find to be much more straight-forward than octal.