I am using Visual Studio Express 2012 for Windows Desktop.
I always get error
Error C4996: 'strtok': This function or variable may be unsafe.
Consider using strtok_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details.
When I try to build the following:
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char the_string[81], *p;
cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok(the_string, ",");
while (p != NULL) {
cout << p << endl;
p = strtok(NULL, ",");
}
system("PAUSE");
return 0;
}
Why am I getting this error even though I define _CRT_SECURE_NO_WARNINGS
, and how do I fix it?
Error C4996 using strtok and strcat
SOLVED
Hello!
I programmed this member function for a «client» class, where I am receiving through command line something like this: host/path1/path2/path3/filename
And in this function I trying to separate the information between the ‘/’ and store it in my class variables host, path and filename (all of them are of type char*)
However this is not working, when compiling I get:
error C4996: 'strtok': This function or variable may be unsafe. Consider using strtok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. error C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
I would like to understand why this functions are «unsafe» and any information about this is well received.
Should I do this another way, like trying to do this with strings?
Should I disable deprecation with _CRT_SECURE_NO_WARNINGS?
I am working in visual studio
Here is my function checkCommand:
bool Client::checkCommand(int argc_, char* arguments) { if (argc_ == 2) { char* tokens[MAXTOKENS] = { }; char* tokenPtr = strtok(arguments, "/"); int i, totalTokens = 0; while (tokenPtr != NULL && totalTokens < MAXTOKENS) { tokens[totalTokens] = tokenPtr; tokenPtr = strtok(NULL, "/"); } this->host = tokens[0]; this->filename = tokens[totalTokens]; this->path = tokens[2]; /*here i concatenate my first path to the rest of the paths*/ for (i = 3; i < totalTokens; i++) { strcat(this->path, tokens[i]); strcat(this->path, "/"); } return true; } else return false; }
thank you!
Error message:
Severity Code Description Item File Line Prohibited status
Error C4996 ‘strtok’: This function or variable may be unsafe. Consider using strtok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. Camera calibration E:\C++\Camera calibration\Camera calibration\Camera calibration.cpp 208
step:
-
Open the error code file with VS2019
-
Right-click the project file name to open the shortcut menu, find the «Properties» option, and enter the project properties page
-
Find «C/C++»——»Preprocessor» in the property page, and click the button where the arrow points
-
Add a command in the edit window below: _CRT_SECURE_NO_WARNINGS
-
Apply and exit after adding
-
Compile and run again to run normally.
I need to print the components of a given char(in this case the numbers which are separated pe whitespece) and I don’t understand why this doesn’t work(doesn’t compile): (or here http://ideone.com/JSrqg5).
The errors are:
error C4996: 'strtok': This function or variable may be unsafe. Consider using strtok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\ellly\documents\visual studio 2013\projects\consoleapplication15446\consoleapplication15446\source.cpp 18 1 ConsoleApplication15446
error C2664: 'char *strcpy(char *,const char *)' : cannot convert argument 1 from 'char' to 'char *' c:\users\ellly\documents\visual studio 2013\projects\consoleapplication15446\consoleapplication15446\source.cpp 21 1 ConsoleApplication15446
And the code:
#include <iostream>
#include <cstring>
using namespace std;
char s[20000], *p, a[5000], separator[] = " ";
int k = 0, i;
void separare();
void afisare();
int main()
{
cout << "Sirul de nr:"; cin.get(s, 100, '\n');
separare();
afisare();
system("pause");
return 0;
}
void separare()
{
p = strtok(s, separator);
while (p)
{
strcpy(a[k], p);
k++;
p = strtok(NULL, separator);
}
}
void afisare()
{
int i;
for (i = 0; i < k; i++)
cout << a[i] << " ";
}
Dettorer
1,2771 gold badge9 silver badges26 bronze badges
asked Dec 10, 2014 at 14:33
11
Your code seems ok, if you are running on linux though, you must check that the file /lib/modules/$(uname -r)/build points to a valid location of your header files (usually in /usr/src/linux-headers-XXXX).
A lot of times after installing new kernel and headers, this link gets broken, and then your programs cannot link to the libraries, and for that reason it won’t compile.
Hope it helps.
By the way you cannot use a[k] for strcpy, as this is dereferencing a single char, while the input must be char*. You should use pointer notation instead, i.e (a+k) would work in this case.
answered Dec 10, 2014 at 15:04
Я использую Visual Studio Express 2012 для рабочего стола Windows.
Я всегда получаю ошибку
Error C4996: 'strtok': This function or variable may be unsafe.
Consider using strtok_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
See online help for details.
Когда я пытаюсь построить следующее:
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char the_string[81], *p;
cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok(the_string, ",");
while (p != NULL) {
cout << p << endl;
p = strtok(NULL, ",");
}
system("PAUSE");
return 0;
}
Почему я получаю эту ошибку, хотя я определяю _CRT_SECURE_NO_WARNINGS
и как ее исправить?
Поделиться
Источник
3 ответа
Ваш #define не работает из-за содержимого вашего предварительно скомпилированного файла заголовка (stdafx.h). Шаблонный выглядит следующим образом:
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
Это последние два #includes, которые вызывают проблему, эти .h файлы сами уже #include string.h. Поэтому ваш #define слишком поздно.
Вместо определения макроса в настройках компилятора вместо этого простым обходным путем является простое перемещение #define в файл stdafx.h. Fix:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
Hans Passant
Поделиться
Это может быть старый пост, но в последнее время у меня была аналогичная проблема.
Я вошел в опции проекта → C/С++ → Preprocessor → добавил _CRT_SECURE_NO_WARNINGS в список определений препроцессора.
Таким образом, вы не должны помещать его в каждый файл.
Martin
Поделиться
Похоже, вы включили параметр компилятора, который заставляет компилятор учитывать все предупреждения как ошибки. Отключите эту опцию или используйте макрос _CRT_SECURE_NO_WARNINGS
Vlad from Moscow
Поделиться
Ещё вопросы
- 1Каково идеальное место для кэширования изображений?
- 0Модульное тестирование отсутствия элемента dom
- 1Почему новый сеанс создается до того, как я войду в систему?
- 1Как сохранить запрос в переменных с помощью C #?
- 0Директива AngularJS для вкладок пользовательского интерфейса BootStrap (проблемы с областью изоляции)
- 0MFC: CMFCToolBar SetButtonStyle не работает со стилем TBBS_PRESSED?
- 1Обещание Resolve возвращает 2 массива один неопределенный
- 0Некоторые основные вопросы о JWT (на стороне сервера и клиента)
- 1Служба Windows с FileWatcher не работает должным образом
- 0Cron Job PHP Foreach отправляет только одну электронную почту / запускает одну строку
- 1Как сопоставить шаблон регулярного выражения только в одной строке?
- 0База данных для хранения списка словарей
- 0Выбор даты угловой UI, приводящий к значению $ valid, равному false
- 0Почему я создал потенциальный блуждающий указатель при удалении здесь в деструкторе?
- 1Получите <a href= людямhttps://www.google.se/ Обработанной> html пакет аджилити ширины адреса
- 0Как вызвать метод / функцию 50 раз в секунду
- 0Safari 100% DIV оставляет место на правой стороне
- 0настройка типа ввода в ng-repeat
- 0Может ли PHP использовать переменные до их определения?
- 1Построение кривой ROC с несколькими классами
- 0JQuery датчик для координат
- 0Как использовать mysql после установки более старой версии mariadb через homebrew?
- 1Получить адрес отправителя SMTP из нового открытого почтового инспектора Outlook с C # (VSTO или погашение), когда настроено несколько учетных записей
- 0Моя Галерея Содержания Javascript — Ошибка Где-то здесь
- 0показать загруженное изображение, прежде чем нажать на кнопку отправить
- 0Boost Unit Test: поймать неудачный тест
- 0Прокрутка страницы как параллакс
- 0Странное поведение Angular 1.3 при копировании элемента в NG-повтор
- 0как скрыть и показать опции выбора для другой панели выбора
- 0Сокращающиеся интервалы окна
- 0т.е. ответный текст не завершен
- 0Как мне запустить этот скрипт в MYSQL?
- 0Проверка формы с помощью jquery, когда в форме не существует, ввод с классом ‘error’
- 1Построение различных графиков networkx в цикле for
- 0Как обновить количество базы данных из действия php
- 0IE слишком медленный при добавлении большого количества HTML в DOM через Javascript
- 0Могу ли я узнать разницу между этими предупреждениями, а также нужны советы по attr?
- 0Codeigniter- Экспорт в CSV Проблемы
- 1временная мертвая зона (ES6) не работает
- 0quickfix bad_cast исключение с взломанным login_message
- 0Добавить / установить заголовок элемента <li>
- 0Ошибка в AngularJS? Различные результаты на Chrome (43) и Firefox (38.0.5)
- 0Создание базового массива объектов JavaScript
- 1Как остановить масштабирование навигационной панели инструментов Matplotlib при обновлении графика?
- 1Python конвертирование из c # Расчет CRC8 из кадра 4/5 байт
- 1Почему эта нейронная сеть выдает предупреждение во время выполнения?
- 1Ищет наличие составного ключа в трех DataFrames и соответственно объединяет DataFrames
- 0C ++ Неопределенная ссылка на функции
- 0Элементы исчезают и исчезают с jQuery, вызывая проблемы
- 1Цвет узлов D3 на основе группы, определенной в CSV