[英]strtok_s function breaking the program
我已經閱讀了有關此功能的大部分已回答問題,但我現在想知道為什么我的代碼打印了令牌但仍然中斷。 我應該使用此函數從只有' '
分隔符的字符串中提取標記並對它們進行一些操作,但我首先嘗試只打印標記,如果這可以正常工作,則在修改標記之后. 這不會發生......我在 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';;
}
}
}
我在控制台中得到了這個結果,這讓我很高興:
但是,我也收到此錯誤,彈出一個名為iosfwd
窗口,箭頭指向一條可能解釋中斷原因的行: return (*_First == 0 ? 0
這是錯誤窗口:
在strtok_s
返回后使用token
作為cout
輸入參數,不測試它是否為空。
這不安全,可能是您崩潰的原因。
請嘗試以下操作:
while (token != NULL)
{
cout << token << '\n';
token = strtok_s(NULL, " ", &next_token);
}
通過這樣做,您可以刪除對cout
的第一個調用。
關於代碼中的以下兩行:
token = strtok_s(NULL, " ", &next_token);
cout << token << '\n';;
您能否嘗試向您的橡皮鴨解釋當strtok_s
() 返回 NULL 以指示沒有更多令牌可以從您的字符串中檢索時會發生什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.