Error c4996 kbhit the posix name for this item is deprecated

I am using the kbhit method on my code. Currently, when i compile my c++ code its showing me this error Severity Code Description Project File Line Suppression State Error C4996 'k...

I am using the kbhit method on my code. Currently, when i compile my c++ code its showing me this error

Severity    Code    Description Project File    Line    Suppression State
Error   C4996   'kbhit': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _kbhit.

This is my partial c++ code:

#ifdef WIN32
            /* enable leaving of endless loop if running under windows, */
            /* necessary to return handles and close driver */


            /* Do I/O Data exchange until a key is hit */
            while (!kbhit())
            {
                if (CIFX_NO_ERROR != (lRet = xChannelIORead(hChannel,
                    0, 0, sizeof(abRecvData),
                    abRecvData,
                    IO_WAIT_TIMEOUT)))
                {
                    printf("Error reading IO Data area!rn");
                    break;
                }
                else
                {
                    printf("IORead Data:");
                    //DumpData(abRecvData, sizeof(abRecvData));
                    if (CIFX_NO_ERROR != (lRet = xChannelIOWrite(hChannel,
                        0, 0, sizeof(abRecvData),
                        abRecvData,
                        IO_WAIT_TIMEOUT)))
                    {
                        printf("Error writing to IO Data area!rn");
                        break;
                    }
                    else
                    {
                        printf("IOWrite Data:");
                        //DumpData(abSendData, sizeof(abSendData));
                        /* Create new output data */
                        memset(abSendData, ulCycle + 1, sizeof(abSendData));
                    }
                }
            }
#endif

Are there any ways to solve this error. Tq.

kirill1059

14 / 14 / 3

Регистрация: 16.04.2013

Сообщений: 404

1

08.12.2013, 14:03. Показов 7940. Ответов 2

Метки нет (Все метки)


Добрый день, подскажите пожалуйста.
При сборке программы выдаёт такую ошибку

Ошибка 1 error C4996: ‘kbhit’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _kbhit. See online help for details.

чем её не нравиться функция kbhit() ?

вот код программы

C++
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <conio.h>
using namespace std;
 
int main()
{
    int i;
    for (i = 0; !kbhit(); i++) cout << i << ' ';
 
    system("pause");
    return 0;
}

Спасибо

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.12.2013, 14:03

Ответы с готовыми решениями:

kbhit
Привет всем. kbhit() умеет различать какая клавиша нажата? или для этого уже что то нужно посложнее?

Аналог kbhit
Подскажите пожалуйста, какую функцию необходимо использовать в С++, чтобы прога поняла, что нажата…

Kbhit() — не определяется
Подпараграф &quot;Вариация на тему цикла for&quot; из книги Шилдта &quot;C++ Базовый курс&quot; предлагает вот такой…

Функция kbhit
как сделать чтобы функция kbhit реагировала не на любую нажатую клавишу, а только на определенную?

2

1404 / 646 / 135

Регистрация: 11.08.2011

Сообщений: 2,299

Записей в блоге: 2

08.12.2013, 14:10

2

kirill1059, это вообще варнинг должен быть. Может у тебя в настройках проекта стоит что-то вроде «Трактовать варнинг как еррор»?



0



324 / 307 / 59

Регистрация: 06.03.2013

Сообщений: 869

08.12.2013, 14:16

3

kirill1059, ну дак и юзайте _kbhit вместо kbhit. any questions?



2



RRS feed

  • Remove From My Forums
  • Вопрос

  • error C4996: ‘kbhit’: The POSIX name for this item is deprecated       How could i solve it?

Все ответы

    • Изменено

      16 декабря 2019 г. 15:10

    • Предложено в качестве ответа
      Castorix31
      16 декабря 2019 г. 16:06
  • Hello,

    If your issue is solved, please «Mark as answer» or «Vote as helpful» post to the appropriate answer , so that it will help other members to find solution quickly if they faces similar issue.

    Best Regards,

    Suarez Zhou


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

title description ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Warning (level 3) C4996

Explains why Compiler warning C4996 happens, and describes what to do about it.

08/30/2022

C4996

C4996

926c7cc2-921d-43ed-ae75-634f560dd317

Your code uses a function, class member, variable, or typedef that’s marked deprecated. Symbols are deprecated by using a __declspec(deprecated) modifier, or the C++14 [[deprecated]] attribute. The actual C4996 warning message is specified by the deprecated modifier or attribute of the declaration.

[!IMPORTANT]
This warning is always a deliberate message from the author of the header file that declares the symbol. Don’t use the deprecated symbol without understanding the consequences.

Remarks

Many functions, member functions, function templates, and global variables in Visual Studio libraries are deprecated. Some, such as POSIX and Microsoft-specific functions, are deprecated because they now have a different preferred name. Some C runtime library functions are deprecated because they’re insecure and have a more secure variant. Others are deprecated because they’re obsolete. The deprecation messages usually include a suggested replacement for the deprecated function or global variable.

The /sdl (Enable Additional Security Checks) compiler option elevates this warning to an error.

Turn off the warning

To fix a C4996 issue, we usually recommend you change your code. Use the suggested functions and global variables instead. If you need to use the existing functions or variables for portability reasons, you can turn off the warning.

Turn off the warning for a specific line of code

To turn off the warning for a specific line of code, use the warning pragma, #pragma warning(suppress : 4996).

Turn off the warning within a file

To turn off the warning within a file for everything that follows, use the warning pragma, #pragma warning(disable : 4996).

Turn off the warning in command-line builds

To turn off the warning globally in command-line builds, use the /wd4996 command-line option.

Turn off the warning for a project in Visual Studio

To turn off the warning for an entire project in the Visual Studio IDE:

  1. Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

  2. Select the Configuration Properties > C/C++ > Advanced property page.

  3. Edit the Disable Specific Warnings property to add 4996. Choose OK to apply your changes.

Disable the warning using preprocessor macros

You can also use preprocessor macros to turn off certain specific classes of deprecation warnings used in the libraries. These macros are described below.

To define a preprocessor macro in Visual Studio:

  1. Open the Property Pages dialog for your project. For information on how to use the Property Pages dialog, see Property Pages.

  2. Expand Configuration Properties > C/C++ > Preprocessor.

  3. In the Preprocessor Definitions property, add the macro name. Choose OK to save, and then rebuild your project.

To define a macro only in specific source files, add a line such as #define EXAMPLE_MACRO_NAME before any line that includes a header file.

Here are some of the common sources of C4996 warnings and errors:

POSIX function names

The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: new-name. See online help for details.

Microsoft renamed some POSIX and Microsoft-specific library functions in the CRT to conform with C99 and C++03 constraints on reserved and global implementation-defined names. Only the names are deprecated, not the functions themselves. In most cases, a leading underscore was added to the function name to create a conforming name. The compiler issues a deprecation warning for the original function name, and suggests the preferred name.

To fix this issue, we usually recommend you change your code to use the suggested function names instead. However, the updated names are Microsoft-specific. If you need to use the existing function names for portability reasons, you can turn off these warnings. The functions are still available in the library under their original names.

To turn off deprecation warnings for these functions, define the preprocessor macro _CRT_NONSTDC_NO_WARNINGS. You can define this macro at the command line by including the option /D_CRT_NONSTDC_NO_WARNINGS.

Unsafe CRT Library functions

This function or variable may be unsafe. Consider using safe-version instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Microsoft deprecated some CRT and C++ Standard Library functions and globals because more secure versions are available. Most of the deprecated functions allow unchecked read or write access to buffers. Their misuse can lead to serious security issues. The compiler issues a deprecation warning for these functions, and suggests the preferred function.

To fix this issue, we recommend you use the function or variable safe-version instead. Sometimes you can’t, for portability or backwards compatibility reasons. Carefully verify it’s not possible for a buffer overwrite or overread to occur in your code. Then, you can turn off the warning.

To turn off deprecation warnings for these functions in the CRT, define _CRT_SECURE_NO_WARNINGS.

To turn off warnings about deprecated global variables, define _CRT_SECURE_NO_WARNINGS_GLOBALS.

For more information about these deprecated functions and globals, see Security Features in the CRT and Safe Libraries: C++ Standard Library.

Unsafe Standard Library functions

'std:: function_name ::_Unchecked_iterators::_Deprecate' Call to std:: function_name with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'

In Visual Studio 2015, this warning appears in debug builds because certain C++ Standard Library function templates don’t check parameters for correctness. Often it’s because not enough information is available to the function to check container bounds. Or, because iterators may be used incorrectly with the function. This warning helps you identify these functions, because they may be a source of serious security holes in your program. For more information, see Checked iterators.

For example, this warning appears in Debug mode if you pass an element pointer to std::copy, instead of a plain array. To fix this issue, use an appropriately declared array, so the library can check the array extents and do bounds checking.

// C4996_copyarray.cpp
// compile with: cl /c /W4 /D_DEBUG C4996_copyarray.cpp
#include <algorithm>

void example(char const * const src) {
    char dest[1234];
    char * pdest3 = dest + 3;
    std::copy(src, src + 42, pdest3); // C4996
    std::copy(src, src + 42, dest);   // OK, copy can tell that dest is 1234 elements
}

Several standard library algorithms were updated to have «dual range» versions in C++14. If you use the dual range versions, the second range provides the necessary bounds checking:

// C4996_containers.cpp
// compile with: cl /c /W4 /D_DEBUG C4996_containers.cpp
#include <algorithm>

bool example(
    char const * const left,
    const size_t leftSize,
    char const * const right,
    const size_t rightSize)
{
    bool result = false;
    result = std::equal(left, left + leftSize, right); // C4996
    // To fix, try this form instead:
    // result = std::equal(left, left + leftSize, right, right + rightSize); // OK
    return result;
}

This example demonstrates several more ways the standard library may be used to check iterator usage, and when unchecked usage may be dangerous:

// C4996_standard.cpp
// compile with: cl /EHsc /W4 /MDd C4996_standard.cpp
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }

    cout << endl;
}

int main()
{
    vector<int> v(16);
    iota(v.begin(), v.end(), 0);
    print("v: ", v);

    // OK: vector::iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    vector<int> v2(16);
    transform(v.begin(), v.end(), v2.begin(), [](int n) { return n * 2; });
    print("v2: ", v2);

    // OK: back_insert_iterator is marked as checked in debug mode
    // (i.e. an overrun is impossible)
    vector<int> v3;
    transform(v.begin(), v.end(), back_inserter(v3), [](int n) { return n * 3; });
    print("v3: ", v3);

    // OK: array::iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    array<int, 16> a4;
    transform(v.begin(), v.end(), a4.begin(), [](int n) { return n * 4; });
    print("a4: ", a4);

    // OK: Raw arrays are checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    // NOTE: This applies only when raw arrays are
    // given to C++ Standard Library algorithms!
    int a5[16];
    transform(v.begin(), v.end(), a5, [](int n) { return n * 5; });
    print("a5: ", a5);

    // WARNING C4996: Pointers cannot be checked in debug mode
    // (i.e. an overrun triggers undefined behavior)
    int a6[16];
    int * p6 = a6;
    transform(v.begin(), v.end(), p6, [](int n) { return n * 6; });
    print("a6: ", a6);

    // OK: stdext::checked_array_iterator is checked in debug mode
    // (i.e. an overrun triggers a debug assertion)
    int a7[16];
    int * p7 = a7;
    transform(v.begin(), v.end(),
        stdext::make_checked_array_iterator(p7, 16),
        [](int n) { return n * 7; });
    print("a7: ", a7);

    // WARNING SILENCED: stdext::unchecked_array_iterator
    // is marked as checked in debug mode, but it performs no checking,
    // so an overrun triggers undefined behavior
    int a8[16];
    int * p8 = a8;
    transform( v.begin(), v.end(),
        stdext::make_unchecked_array_iterator(p8),
        [](int n) { return n * 8; });
    print("a8: ", a8);
}

If you’ve verified that your code can’t have a buffer-overrun error, you can turn off this warning. To turn off warnings for these functions, define _SCL_SECURE_NO_WARNINGS.

Checked iterators enabled

C4996 can also occur if you don’t use a checked iterator when _ITERATOR_DEBUG_LEVEL is defined as 1 or 2. It’s set to 2 by default for debug mode builds, and to 0 for retail builds. For more information, see Checked iterators.

// C4996_checked.cpp
// compile with: /EHsc /W4 /MDd C4996_checked.cpp
#define _ITERATOR_DEBUG_LEVEL 2

#include <algorithm>
#include <iterator>

using namespace std;
using namespace stdext;

int main() {
    int a[] = { 1, 2, 3 };
    int b[] = { 10, 11, 12 };
    copy(a, a + 3, b + 1);   // C4996
    // try the following line instead:
    // copy(a, a + 3, checked_array_iterator<int *>(b, 3));   // OK
}

Unsafe MFC or ATL code

C4996 can occur if you use MFC or ATL functions that were deprecated for security reasons.

To fix this issue, we strongly recommend you change your code to use updated functions instead.

For information on how to suppress these warnings, see _AFX_SECURE_NO_WARNINGS.

Obsolete CRT functions and variables

This function or variable has been superseded by newer library or operating system functionality. Consider using new_item instead. See online help for details.

Some library functions and global variables are deprecated as obsolete. These functions and variables may be removed in a future version of the library. The compiler issues a deprecation warning for these items, and suggests the preferred alternative.

To fix this issue, we recommend you change your code to use the suggested function or variable.

To turn off deprecation warnings for these items, define _CRT_OBSOLETE_NO_WARNINGS. For more information, see the documentation for the deprecated function or variable.

Marshaling errors in CLR code

C4996 can also occur when you use the CLR marshaling library. In this case, C4996 is an error, not a warning. The error occurs when you use marshal_as to convert between two data types that require a marshal_context Class. You can also receive this error when the marshaling library doesn’t support a conversion. For more information about the marshaling library, see Overview of marshaling in C++.

This example generates C4996 because the marshaling library requires a context to convert from a System::String to a const char *.

// C4996_Marshal.cpp
// compile with: /clr
// C4996 expected
#include <stdlib.h>
#include <string.h>
#include <msclrmarshal.h>

using namespace System;
using namespace msclr::interop;

int main() {
   String^ message = gcnew String("Test String to Marshal");
   const char* result;
   result = marshal_as<const char*>( message );
   return 0;
}

Example: User-defined deprecated function

You can use the deprecated attribute in your own code to warn callers when you no longer recommend use of certain functions. In this example, C4996 is generated in two places: One for the line the deprecated function is declared on, and one for the line where the function is used.

// C4996.cpp
// compile with: /W3
// C4996 warning expected
#include <stdio.h>

// #pragma warning(disable : 4996)
void func1(void) {
   printf_s("nIn func1");
}

[[deprecated]]
void func1(int) {
   printf_s("nIn func2");
}

int main() {
   func1();
   func1(1);    // C4996
}

Я использую kbhit метод в моем коде. В настоящее время, когда я компилирую код на C ++, он показывает мне эту ошибку

Severity    Code    Description Project File    Line    Suppression State
Error   C4996   'kbhit': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _kbhit.

Это мой частичный код C ++:

#ifdef WIN32
/* enable leaving of endless loop if running under windows, */
/* necessary to return handles and close driver *//* Do I/O Data exchange until a key is hit */
while (!kbhit())
{
if (CIFX_NO_ERROR != (lRet = xChannelIORead(hChannel,
0, 0, sizeof(abRecvData),
abRecvData,
IO_WAIT_TIMEOUT)))
{
printf("Error reading IO Data area!rn");
break;
}
else
{
printf("IORead Data:");
//DumpData(abRecvData, sizeof(abRecvData));
if (CIFX_NO_ERROR != (lRet = xChannelIOWrite(hChannel,
0, 0, sizeof(abRecvData),
abRecvData,
IO_WAIT_TIMEOUT)))
{
printf("Error writing to IO Data area!rn");
break;
}
else
{
printf("IOWrite Data:");
//DumpData(abSendData, sizeof(abSendData));
/* Create new output data */
memset(abSendData, ulCycle + 1, sizeof(abSendData));
}
}
}
#endif

Есть ли способы решить эту ошибку. Тя.

-1

Решение

«Есть ли способы решить эту ошибку» — да. Решение в прямом смысле часть сообщения об ошибке: «Вместо этого используйте совместимое имя ISO C и C ++: _kbhit».

2

Другие решения

Других решений пока нет …

I have a problem with my program that repeat names,it work correctly first then it glitch out when you use the program loop many times,and

1
2
3
4
5
6
 else

    {
       cout << "denied";
       delay(3);
    }

keep repeating itself until I close the program.

here’s the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  #include <iostream>
#include <string>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>


using namespace std;

void repeation(int maxx);

void delay (float de)
{
    Sleep(de*1000);
}
void command(string choose)
{
    if(choose == "yes" || choose == "YES"){
        int number;
        cout << "enter the number of repeation ";
        cin >> number;
        cout << "press any key to stop the repeat";
        delay(2);
        repeation(number);
        ;
    }
    else

    {
       cout << "denied";
       delay(3);
    }
}


void repeation(int maxx)
{
    int numb = 0;
    while( maxx > numb && !kbhit())
        {cout << "any thing";
        delay(0.01);
        numb ++;
 }
   numb = 0;
   delay(2);
        }



int main()
{
    delay(1);
    while (1){
//............................------------------------------...........................;
    cout << "                     repeatation program                                       "<<endl;
    cout <<"                 ____________________________                                   nn";
    cout <<"press any yes to choose to repeat " << "= ";
    string choice;
    cin >>choice;
    cout <<"________________________________ nnn";
    command(choice);
    system("cls");
    }

}

so can you check it and tell me if something wrong with my code btw I tried
to remove conio.h and it did nothing.

Last edited on

Explain exactly what you are inputtng into the program to cause it to «glitch» out.

Is it possible you’re accidentally putting a letter or something invalid into your int number?

On line 22, check to make the the input is valid by changing line 22 to

1
2
3
4
5
6
7
if (!(cin >> number))
{
    cout << "Invalid numbern";
    number = 0;
    cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    cin.clear();
}

Also #include <limits> at the top.

and then try to repeat the issue.
The combination of cin.ignore() + cin.clear() resets your cin buffer into a clean state to allow it to correctly receive input again.

Last edited on

the glitch was that every thing was missed up in the console and denied keep repeating,
so I tried your solution now it says access denied for a few seconds then every thing is back

to normal you can’t so program and just type character or a very big number like(2000*10^9)

when the program ask you for a number and you see the glitch and thank you.

Your code works fine for me. I had to beat on it a little to get it working (not on a windows system) but it worked once I fixed the OS specific junk.

Maybe try my version? It will quickly run and tell you if it works or not, since I wrote my own sleep that runs instantly (after getting tired of waiting on it). Once you see it is working you can put your delays back in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream> //fixed headers to c++ versions
#include <string>   
#include <ctime>
#include <cstdlib>

void sleep(int x)
{
  return;
}

using namespace std;

void repeation(int maxx);

/*void delay (float de) //code bloat
{
    sleep(de*1000);
}*/

void command(string choose)
{
    if(choose == "yes" || choose == "YES")
	{
        int number;
        cout << "enter the number of repeation ";
        cin >> number;
        cout << "press any key to stop the repeat";
        //delay(2);
		sleep(2000);
        repeation(number);
    }
    else
    {
       cout << "denied";
       sleep(3000);
    }
}


void repeation(int maxx)
{
    int numb = 0;
    while( maxx > numb) // && !kbhit())
	   {
		    cout << "any thingn";
			sleep(10);
			numb ++;
	   }
   numb = 0;
   sleep(2000);
}



int main()
{    
    while (1)
	{
//............................------------------------------...........................;
    cout << "                     repeatation program                                       "<<endl;
    cout <<"                 ____________________________                                   nn";
    cout <<"press any yes to choose to repeat " << "= ";
    string choice;
    cin >>choice;
    cout <<"________________________________ nnn";
    command(choice);
    system("cls");
    }

}

now, it may not do what you expect. it repeats anything N times if you type in yes, which is strange behavior, but ok.

Last edited on

thank you for your time but it have the same problem @jonnin,

and thanks to ganado your code make the file works and the glitch apears just a second

and disappear.

Yes, I did not change anything, I just made it run without the sleeps, and it worked on my machine if I entered integers for the integer so I stopped there. I did not realized you wanted to check for bad inputs.

you may still want to fix your C headers for good practice.

Last edited on

@ganado when I tried your solution if

1
2
3
4
5
6
7
 (!(cin >> number))
{
    cout << "Invalid numbern";
    number = 0;
    cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    cin.clear();rs 
}

it says invalid,and the glitch appears for a few seconds and disappear when I write an invalid character.

Last edited on

Hello ahmedddddddd,

Sorry this is long it kink of got away from me, so it is in two parts.

Looking at your program it is easy to see that it is written for Windows.What is not easy to figure out is what IDE you are using, if any, as it would help in answering your questions.

I am not saying that your program is totally wrong as it can be made to work, but there are some better way to do what you did.

The following code works and I will use it to explain where you are having problems.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <cctype> // <--- Added. For "std::tolower()" and "std::toupper()".
#include <iostream>
#include <iomanip>  // <--- Not needed in this program, but will be used in the future. For "std::setpercision()" and "std::setw()".
#include <string>
#include <conio.h>
#include <windows.h>
#undef min
#undef max
#include <limits>
//#include <ctime>
#include <cstdlib>

#include <chrono>
#include <thread>

//using namespace std;  // <--- Best not to use.
// A recent post that is worth reading. http://www.cplusplus.com/forum/beginner/258335/

//void repeation(int maxx); // <--- Not needed if you put the functions in this order.

void delay(DWORD de)
{
	Sleep(de);
}

void repeation(int maxx)
{
	int numb = 0;

	while (maxx > numb && !_kbhit())
	{
		std::cout << "n  any thing";

		delay(1000);

		numb++;
	}

	if (_kbhit())
		_getch();

	//numb = 0; // <--- Not needed. taken care of by line 28.

	delay(2000);
}

void command(char choose)
{
	constexpr size_t MINNUM{ 0 }, MAXNUM{ 10 };

	if (choose == 'y' || choose == 'Y') // <--- Should be done in "main" not here.
	{
		int number;

		std::cout << "n Enter the number of repeation: ";
		std::cin >> number;

		//if (!(std::cin >> number))
		//{
		//	std::cout << "n    Invalid number!n";
		//	number = 0; // <--- Set to zero here for the function call on line 108.
		//	std::cin.clear();
		//	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
		//}
		//else
		//	std::cout << "n Press any key to stop the repeat.n";

		//while (!std::cin)
		//{
		//	std::cout << "n    Invalid number!n";

		//	number = 0; // <--- Set to zero here for the function call on line 108.

		//	std::cin.clear();
		//	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

		//	std::cout << "n Enter the number of repeation: ";
		//	std::cin >> number;
		//}

		while (!std::cin || (number < MINNUM || number > MAXNUM))
		{
			if (!std::cin)
			{
				std::cout << "n    Invalid number!n";

				number = 0;

				std::cin.clear();
				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');  // <--- Requires header file <limits>.;

				std::cout << "n Enter the number of repeation: ";
				std::cin >> number;
			}
			else
			{
				std::cout << "n Number out of range! Range is 1 - 10.n";

				std::cout << "n Enter the number of repeation: ";
				std::cin >> number;
			}
		}

		std::cout << "n Press any key to stop the repeat.n";

		delay(2000);

		repeation(number);

	}
	else
	{
		std::cout << "n    Denied.";
		delay(1000);
	}
}

int main()
{
	std::this_thread::sleep_for(std::chrono::milliseconds(1000));  // Requires header files "chrono" and "thread".

	while (1)
	{
		//............................------------------------------...........................;
		std::cout << "nn                     repeatation program                                       " << std::endl;
		std::cout << "                 ____________________________                                   nn";
		std::cout << "n Enter y to choose to repeat: ";

		char choice;

		std::cin >> choice;

		std::cout << "________________________________ nn";

		command(choice);

		if (std::toupper(choice) != 'Y')  // <--- An alternative for the if condition. And, if moved up, an alternative to the if/else in the "command" function.
		{
			// <--- A "cout" statement of your choice. e.g., "Denied.".
			break;
		}

		system("cls");
	}

	return 0;
}

Starting with the header files.As jonnin mentioned you should fix your header files.Mixing C and C++ header files is not always a good idea.Sometimes you have no choice like with «Windows.h» many of the C header files do have a C++ version that starts with «c» followed by the C file name and no extension like «cstdlib».At http ://www.cplusplus.com/reference/ click the «+» next to «C Library» to see the C++ equivalent of the C header file. By clicking on the file name you can see what is available for the given header files.

The «cctype» is optional for this program.I included and used it as an example of what could be done.

«iomanip» is not needed for this program, but you might as well get use to seeing and using it because it will be used in the future.

«conio.h»:

salem c once wrote :

#include<conio.h>
Obsolete since 1990, when the world stopped using DOS as a primary operating system.

Another problem here is that your «conio.h» may be old enough that it might contain functions that are no longer available in the newer versions of the header file.And even then the header file is for backward compatibility and not meant to be used in newer programs.

A couple of years ago when I first tried to mix «Windows.h» and «limits» trying to use the linestd::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); I had a problem with the «max()» that «limits» wanted to use.As I found out later «Windows.h» defines the macros of «min» and «max» as:
#define min(a, b) (((a) < (b)) ? (a) : (b)) and
#define max(a, b) (((a) > (b)) ? (a) : (b))
Unfortunately the «min» and «max» in «limits» is different than the above code hence the#undef s before you include «limits». This will let the «std::cin.ignore(…)» work properly.

«ctime» or «time.h», you should use the «ctime», is not used in your program.As such it is not needed and is just putting extra code into your program that you are not using.

The header fileschrono and thread are there to show you an example replacement for the «Sleep()» you are using.

For usingusing namespace std; read the link.It is worth the time as is http ://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

Line 19 the prototype can be deleted if you order your functions as I have done.The reason you needed the prototype is because you were trying to call a function that had not yet been defined.This way «delay» is define and compiled before «repeation» used it and both functions are defined and compiled before «command» uses them.If you are going to prototype a function you might as well prototype all the functions just to be safe.Also prototyping all functions means that you do not have to worry about the order the functions are done in.

In the «delay» function Microsoft has this to say about «Sleep» :

void Sleep(
DWORD dwMilliseconds
);

Where «DWORD» istypedef unsigned long DWORD; on my computer/IDE/header files. It is possible that this could be different with a different compiler and header files.Your use of sending a «float», a «double» is the preferred floating point type these days, to the function which eventually is stored in a «DWORD» could cause possible data loss when the decimal portion is dropped to store the whole number.The one place you used the «float» by sending «0.01» to the function ended up with a value of(10) and (10) milliseconds is not enough time to see any delay.

By reworking the «delay» function you could just as easily replace «delay» in the program with «Sleep» and eliminate the need for the function.

End part 1.

Part 2.

In the «repeation» function there is not much I had to change there.Thekbhit() and getch(); I had to change to_kbhit() and _getch(); for my compiler to accept them with out any problem.With out the underscore I get the message : «
Error C4996 ‘kbhit’ : The POSIX name for this item is deprecated.Instead, use the ISO C and C++ conformant name : _kbhit.See online help for details. problem with a repeater f : vs 2017problem with a repeaterproblem with a repeatermain v1.cpp 30″. The part in bold is the most important part. The rest will be different on your computer.

I also had to add line 39 and 40 to eat what was entered for the «_kbhit()» so that it would not show up later in the program as it did.

Line 42 is unnecessary because you never use «numb» before the functions ends at which time you loose the variable «numb» when the function ends.The next time the function is call you define «numb» and set it to zero before you use it and everything works fine.

In the function «command» the first line is a better way to deal with the uncommented while condition than using magic numbers, as they are called.

As the comment says the if/else should be in «main» and not here.By the time this function is called you should already know that you need to be here.

The first if statement is based on Ganado‘s suggestion although I added the else part. If you can not figure out why let me know. It took me a little thought before I finally understood how it works.

The first while loop just checks for something other than a number being entered into «number». As formatted input «cin» is expecting a numeric value to be entered and when something that is not a number is entered it causes the stream to fail which needs to be dealt with.

The second while loop is much like the first while loop except the it also checks that the number entered is with in the range of «MINNUM» and «MAXNUM».This program is not a good example for using the constant variables, but it can give you an idea for the future.

The only issue I found with Ganado‘s suggestion is the order of the std::cin.ignore(...); and the std::cin.clear();. When I tried the «ignore» before the «clear» this did not seem to work, but when I reversed the order it worked fine. Not sure why, but I have always seen and used the «clear» before the «ignore».

Should you use the if/else statement you will need to put a comment on line 106 for it to work properly.

For «main» the first line is an alternative to using the «Sleep()» function which is specific to Windows and not everyone can use it as jonnin has mentioned.This line is also a more portable form of code that anyone can use.

With in the line ofstd::this_thread::sleep_for(std::chrono::milliseconds(1000)); the only two parts you need to worry about are using either «milliseconds» or «seconds» and the number in(). The number in() can either be zero or greater for «milliseconds» where 500 is 1/2 second, 1000 is one second and 1500 is one and 1/2 seconds.For seconds this is a whole number zero or greater like 1, 2, 3 etc. and there is no partial seconds.

I believe the «glitch» you are trying to describe starts with the while loop.As you have written it is an endless loop with no way out.The if statement I added fixes this problem.Should you move the if statement on line to somewhere above line 135 you will be doing your check in «main», where it should be, and not the «command» function where it is now.

The «system» anything should be avoided as it could leave your program and computer vulnerable to attack.

The last point is the variable «choice». As a «std::string» you can either accept «yes» or «YES» as the only two possible choices and consider anything else as invalid or have a very large if statement trying to account for every possible way of spelling «yes» with lower case and upper case letters and that does not consider any way of misspelling the word.It is better to define «choice» as a «char» and only accept one letter to deal with.A point to consider here is to keep it simple for everyone.

Some of the code I have is not required that you use it, but offered as a suggestion or alternative to what you have done.

Hope that helps,

Andy

ok I dont undrstand anything but thank you very very much I will learn then see you tobic so I can see if I will understand

Hello ahmedddddddd,

Just to let you know your link did not work for me. I do not know if it is out dated or expired or maybe I have to sign up with the web site. It could be either or a combination of problems.

Having worked with C++ for awhile all the code posted here makes sense to me, but I realize that it may not be understandable to people new to the code and syntax.

If you do not understand something let me know what that is and I will try to explain it better.

Andy

Learn why this error appears in your C++ code and how to solve it.

For newbies in C++ using modern tools may become a big headache, specially when the VS version of your school is pretty old and you have the latest version of VS at home. One of the most known exercises for students, is the famous hello world in this language. Playing with a console application, the exercise is simple, print «hello world» and keep the console open to see the printed message. According to the programming style of your teacher you may receive an example snippet using cout:

#include <iostream>
#include <conio.h>

using namespace std;

void main(void)
{
	cout << "Hello World" << endl;

	getch();
}

Or using printf to print the text in the console:

#include <iostream>
#include <conio.h>

void main(void)
{
	printf("Hello World");

	getch();
}

Both scripts are totally valid and they use the getch method to keep the console open. They should work normally in the compilers of the school where VS is always outdated, however, if you use a modern compiler to compile any of the previous examples (using latest version of Visual Studio), you will face the exception. The problem is that the getch method is a non-standard function, and MS compilers have traditionally offered those under two names, but Microsoft decided to define the name without underscore deprecated, because those names are reserved for the programmer.

Solution

The most simple workaround for this issue is to use the _getch method with an underscore as prefix:

#include <iostream>
#include <conio.h>

using namespace std;

void main(void)
{
	cout << "Hello World" << endl;

	// Use the getch method with a prefixed underscore
	_getch();
}

This method works the same but won’t be recognized as deprecated. You can as well use the cin.get method of the std namespace:

#include <iostream>
#include <conio.h>

using namespace std;

void main(void)
{
	printf("Hello World");

	// Allow the input of text in the command line
	// this will keep the console open
	cin.get();
}

Happy coding !

Понравилась статья? Поделить с друзьями:
  • Error c4996 getch
  • Error c4996 fopen this function or variable may be unsafe
  • Error c4716 должна возвращать значение
  • Error c4703 используется потенциально неинициализированная локальная переменная указатель
  • Error c4700 использована неинициализированная локальная переменная