[英]strtok_s function breaking the program
I already read most of the answered questions about this function but I would like to now why is my code printing the tokens and yet breaking.我已经阅读了有关此功能的大部分已回答问题,但我现在想知道为什么我的代码打印了令牌但仍然中断。 I should use this function to extract the tokens from a string that has only the
' '
separator and to do some operations on them, but I tried first to just print the tokens, and if this would have worked perfectly, after to modify the tokens.我应该使用此函数从只有
' '
分隔符的字符串中提取标记并对它们进行一些操作,但我首先尝试只打印标记,如果这可以正常工作,则在修改标记之后. This is not happening ... I wrote the code guided by the Help Viewer in Visual Studio 2015:这不会发生......我在 Visual Studio 2015 中编写了由帮助查看器指导的代码:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{ char s[50] = "testing the strtok_s function", *token = NULL, *next_token = NULL;
// Establish string and get the first token:
token = strtok_s(s, " ", &next_token);
cout << token << '\n';
// While there are tokens in s:
while (token != NULL)
{ //Get the next token:
if (token != NULL)
{ token = strtok_s(NULL, " ", &next_token);
cout << token << '\n';;
}
}
}
I get this result in the console, which makes me happy:我在控制台中得到了这个结果,这让我很高兴:
But, I also get this error, and a window called iosfwd
pops and a arrow points on a line that probably explains the breaking reason: return (*_First == 0 ? 0
但是,我也收到此错误,弹出一个名为
iosfwd
窗口,箭头指向一条可能解释中断原因的行: return (*_First == 0 ? 0
This is the error window:这是错误窗口:
You use token
as input parameter of cout
after the return of strtok_s
, without testing whether it is null or not.在
strtok_s
返回后使用token
作为cout
输入参数,不测试它是否为空。
This is not safe and is probably the reason of your crash.这不安全,可能是您崩溃的原因。
Try the following instead:请尝试以下操作:
while (token != NULL)
{
cout << token << '\n';
token = strtok_s(NULL, " ", &next_token);
}
By doing so, you could remove the first call to cout
.通过这样做,您可以删除对
cout
的第一个调用。
Regarding the following two lines in your code:关于代码中的以下两行:
token = strtok_s(NULL, " ", &next_token);
cout << token << '\n';;
Can you try explaining to your rubber duck what happens here when strtok_s
() returns NULL to indicate that there are no more tokens to retrieve from your string?您能否尝试向您的橡皮鸭解释当
strtok_s
() 返回 NULL 以指示没有更多令牌可以从您的字符串中检索时会发生什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.