How do the puts and gets functions work?

The problem here is, for an input like abc XYZ the code scanf(“%s”,name); reads only the “abc” part and the “XYZ” is left in the input buffer. The later gets() read that, and puts() prints that. As you don’t have a newline after the printf(), the output is not flushed and the outcome of the … Read more

How to use sscanf correctly and safely

The scanf family of function cannot be used safely, especially when dealing with integers. The first case you mentioned is particularly troublesome. The standard says this: If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined. Plain and simple. … Read more

Using scanf with NSStrings

The scanf function reads into a C string (actually an array of char), like this: char word[40]; int nChars = scanf(“%39s”, word); // read up to 39 chars (leave room for NUL) You can convert a char array into NSString like this: NSString* word2 = [NSString stringWithBytes:word length:nChars encoding:NSUTF8StringEncoding]; However scanf only works with console … Read more

whitespace in the format string (scanf)

Whitespace in the format string matches 0 or more whitespace characters in the input. So “%d c %d” expects number, then any amount of whitespace characters, then character c, then any amount of whitespace characters and another number at the end. “%dc%d” expects number, c, number. Also note, that if you use * in the … Read more

Format specifiers for uint8_t, uint16_t, …?

They are declared in <inttypes.h> as macros: SCNd8, SCNd16, SCNd32 and SCNd64. Example (for int32_t): sscanf (line, “Value of integer: %” SCNd32 “\n”, &my_integer); Their format is PRI (for printf)/SCN (for scan) then o, u, x, X d, i for the corresponding specifier then nothing, LEAST, FAST, MAX then the size (obviously there is no … Read more