关于Begining C中strtok_s函数讲解的疑问
Begining C中文第五版第六章217页,例子6.7中对strtok_s使用了4个参数(str,str_size,delimiters,ptr)代码如下:
程序代码:
// Program 6.7 Find all the words #define __STDC_WANT_LIB_EXT1__ 1 // Make optional versions of functions available #include <stdio.h> #include <string.h> #include <stdbool.h> int main(void) { char delimiters[] = " \".,;:!?)("; // Prose delimiters char buf[100]; // Buffer for a line of keyboard input char str[1000]; // Stores the prose to be tokenized char* ptr = NULL; // Pointer used by strtok_s() str[0] = '\0'; // Set 1st character to null size_t str_len = sizeof(str); size_t buf_len = sizeof(buf); printf("Enter some prose that is less than %zd characters.\n" "Terminate input by entering an empty line:\n", str_len); // Read multiple lines of prose from the keyboard while(true) { if(!gets_s(buf, buf_len)) // Read a line of input { printf("Error reading string.\n"); return 1; } if(!strnlen_s(buf, buf_len)) // An empty line ends input break; if(strcat_s(str, str_len, buf)) // Concatenate the line with str { printf("Maximum permitted input length exceeded.\n"); return 1; } } printf("The words in the prose that you entered are:\n", str); // Find and list all the words in the prose unsigned int word_count = 0; char * pWord = strtok_s(str, &str_len, delimiters, &ptr); // Find 1st word if(pWord) { do { printf("%-18s", pWord); if(++word_count % 5 == 0) printf("\n"); pWord = strtok_s(NULL, &str_len, delimiters, &ptr); // 编译出错的地方,编译器报错不应该有4个参数 }while(pWord); // NULL ends tokenizing printf("\n%u words found.\n", word_count); } else printf("No words found.\n"); return 0; }
我在微软官网文档上找到的的sample经过检验,可以顺利编译
代码如下:
程序代码:
// crt_strtok_s.c // In this program, a loop uses strtok_s // to print all the tokens (separated by commas // or blanks) in two strings at the same time. // #include <string.h> #include <stdio.h> char string1[] = "A string\tof ,,tokens\nand some more tokens"; char string2[] = "Another string\n\tparsed at the same time."; char seps[] = " ,\t\n"; char *token1 = NULL; char *token2 = NULL; char *next_token1 = NULL; char *next_token2 = NULL; int main( void ) { printf( "Tokens:\n" ); // Establish string and get the first token: token1 = strtok_s( string1, seps, &next_token1); token2 = strtok_s ( string2, seps, &next_token2); // While there are tokens in "string1" or "string2" while ((token1 != NULL) || (token2 != NULL)) { // Get next token: if (token1 != NULL) { printf( " %s\n", token1 ); token1 = strtok_s( NULL, seps, &next_token1); } if (token2 != NULL) { printf(" %s\n", token2 ); token2 = strtok_s (NULL, seps, &next_token2); } } }
请问这个是什么原因呢?是书上写错了吗?
另外还有一个问题就:
strtok_s( NULL, seps, &next_token1);//第三个参数为什么要取地址符呢?