Меню

System pause c ошибка

System pause error

So, I have done a basic calculator program for college, but when you execute the calculation it prints the answer and the program closes. I have tried system(«pause») but it still doesn’t change anything and I do have iostream and all the #includes needed for it.

This is my 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
#include "stdafx.h"
#include <iostream>
#include <Windows.h>

using namespace std;

int main()
{
	char op;
	float num1, num2;

	cout << "Please enter operator (+ , - , * or /) ";
	cin >> op;

	cout << "Enter your two numbers you wish to calculate ";
	cin >> num1;
	cin >> num2;


	switch (op)
	{
	case '+':
		cout << num1 + num2;
		break;

	case '-':
		cout << num1 - num2;
		break;

	case '*':
		cout << num1*num2;
		break;


	case '/':
		cout << num1 / num2;
		break;

	default:
		// if the operator is other than specified it will give an error
		cout << "error, invalid operator please try again. ";
		break;


	}
	return 0;

}

Last edited on

It seems you are using Visual Studio so try ctrl+F5 to run it.

Yes I can run it and things but I don’t want it to close immediately after it prints the calculation

Hello b487097,

Some quick research showed me that «stdio.h» was the header file used for the «system(«pause»);».

Your code above does not show the use of «system», so I am wondering if you are missing a header file or if your usage is wrong? A lot of programs I white include «Windows.h» and I have not had any problem using a system call.

Quite often I will include «conio.h» and use this code at the end of the program while working with the program and than remove it when I am finished.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//#define RELEASE  // First line in the file. Uncomment when testing is finished.

#ifndef RELEASE
#include <conio.h>
#endif

// Program here

#ifndef RELEASE
std::cout << "nnnn Press anykey to continue";
_getch();
#endif

return 0;
}  // End of main 

I use «_getch()» because my compiler complains about «getch()».

A better way to avoid using «system(«pause»);» would be to wrap lines 12 — 45 in a do/while loop with the while condition as } while (cont); with «cont» defined as bool cont{ true };. Then in the case statements add:

1
2
3
4
case 'q':
case 'Q':
    cont = false;
    break;

Adjust line 12 to add ‘q’ to quit nd you will not have to worry about a pause at the end of the program.

Hope that helps,

Andy

Last edited on

@MikeyBoy,

Sorry. I did say it was quick not in-depth I was rushed at the time and did not go as far as I would normally do. Also I have written programs which include «Windows.h» and have had no problem using «system»

I will strive to do better next time.

Andy

Sorry. I did say it was quick not in-depth I was rushed at the time and did not go as far as I would normally do.

I’m kinda curious as to which source you found that told you that stdio.h — a C header file, not a C++ one — was the one you needed for system. Whatever source that was, I’d advise not trusting it in future, and find a more trustworthy source.

I have written programs which include «Windows.h» and have had no problem using «system»

You’re aware that header files include other header files, right?

@MikeyBoy,

I do not remember where I did the search from. It was either Google or on this site. Either way I just checked the first link or two that came up. Where ever it was I felt that it was good information. I see now that I need to be more careful in the future.

Yes, I do know that a header file can include others. I actually wrote a header file that includes another that includes another. And before you say it I do know that «Windows.h» is something I should not be using, but it like «conio.h» they work with some of the functions I use,, but they are mostly for my use not everyone else. At least until I can find something better.

Thanks for the input. Well taken,

Andy

No problem. For reference information, cppreference.com is an excellent and reliable source, and the reference section on here is good too.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • Hello,

    Can someone please explain why system(«pause») is not being recognized in the following sample code in 2010 Express?  Thanks! Dustin

    // Helloworld.cpp : Defines the entry point for the console application.

    //

    #include
    «stdafx.h»

    int _tmain(int argc, _TCHAR* argv[])

    {

           printf(«Hello, World!n»);

           system(«pause»);

          
    return 0;

    }

    1>—— Build started: Project: Helloworld, Configuration: Debug Win32 ——

    1>  Helloworld_2.cpp

    1>z:9 c programmingsample programshelloworldhelloworld_2.cpp(10): error C2039: ‘system’ : is not a member of ‘std’

    1>z:9 c programmingsample programshelloworldhelloworld_2.cpp(10): error C3861: ‘system’: identifier not found

    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Answers

  • did you supply the correct header?


    Microsoft Test — http://tester.poleyland.com/

    • Proposed as answer by

      Friday, October 15, 2010 7:18 PM

    • Marked as answer by
      Yi Feng Li
      Friday, October 22, 2010 2:58 AM

  1. 03-18-2011


    #1

    dubbin240 is offline


    Registered User


    System Pause Error please help

    Code:

    [QUOTE]#include<stdio.h>
    
    int main () {
    int i,j,max_c, max_j;
    int num_shows;
    
        
        FILE * fin;
        fin = fopen("ucfidol.txt","r");
        
        
        fscanf(fin,"%d", &num_shows);
        printf("%dn",num_shows);
        fscanf(fin,"%d",&max_c);
        printf("Number of contestants = %dn", max_c);
        fscanf(fin,"%d",&max_j);
        printf("Number of judges = %dn", max_j);
        
        
    
    //int scores[max_c][max_j];
        //for(i=1;i<=max_c;i++)
            //fscanf(fin,"%d",&max_c);
        //for(j=1;j<=max_j,j++)
            //fscanf(fin,"%d",&max_j);
        
        
        
        
        fclose(fin);
    
    system("PAUSE");

    I am trying to write a code but I keep getting an error with the system pause. I cant seem to figure it out. Even for other codes I have been trying to write.


  2. 03-18-2011


    #2

    rags_to_riches is offline


    Registered User



  3. 03-18-2011


    #3

    dubbin240 is offline


    Registered User


    For my class our teacher told us to. This is the only way we learned how to keep the output window open


  4. 03-18-2011


    #4

    quzah is offline


    ATH0

    quzah's Avatar


    Quote Originally Posted by dubbin240
    View Post

    I am trying to write a code but I keep getting an error with the system pause.

    What error?

    Quote Originally Posted by dubbin240
    View Post

    I cant seem to figure it out.

    I can’t either, because you didn’t tell me what error you got.

    Code:

    #include<stdilb.h>
    #include<stdio.h>
    int main( void )
    {
        system( "pause" );
        printf( "error?n" );
        return 0;
    }

    If you don’t get an error there, then system isn’t your problem. So, what error are you getting?

    Quzah.

    Hope is the first step on the road to disappointment.


  5. 03-18-2011


    #5

    dubbin240 is offline


    Registered User


    I attached a snip of the error

    Attachment 10430

    Code:

    //int scores[max_c][max_j];
        //for(i=1;i<=max_c;i++)
            //fscanf(fin,"%d",&max_c);
        //for(j=1;j<=max_j,j++)
            //fscanf(fin,"%d",&max_j);

    Also Im not too good with arrays. If I want to read in from a file and store the numbers as an array would this be close?


  6. 03-18-2011


    #6

    quzah is offline


    ATH0

    quzah's Avatar


    See the top two lines of my example? Those are #include directives. They basically say «use the following file». stdlib.h is required for the use of the system function.

    Anytime you see ‘X is undeclared’, it means you are either trying to call a function or variable that it knows nothing about. It doesn’t know anything about it, because it only knows about what is above it in the file. If you haven’t included the appropriate headers at that point, it knows nothing of what the hold.

    edit — for your array edit question

    Arrays are basically like drawers in a cabinet. Each drawer holds whatever type the array is. The drawers of an array of integers each store one integer:

    This would have five drawers, each one holding one int. To put something in one directly:

    Code:

    array[ 2 ] = 12345;

    To put something in with say, scanf, we can do:

    Code:

    scanf( "%d", & array[ 2 ] );

    To put something in each drawer in a loop:

    Code:

    int x = 0;
    for( x = 0; x < 5; x++ )
        scanf( "%d%*c", & array[ x ] );

    Or something to that effect.

    Quzah.

    Last edited by quzah; 03-18-2011 at 05:32 PM.

    Hope is the first step on the road to disappointment.


  7. 03-18-2011


    #7

    CommonTater is offline


    Banned


    Quote Originally Posted by dubbin240
    View Post

    #include stdlib.h


  8. 03-18-2011


    #8

    dubbin240 is offline


    Registered User


    ok thanks that helped…its weird I have never used the standard library but I have always used system pasue


  9. 03-18-2011


    #9

    CommonTater is offline


    Banned


    Quote Originally Posted by dubbin240
    View Post

    ok thanks that helped…its weird I have never used the standard library but I have always used system pasue

    Well, for future… everything that’s not a C keyword is either part of the standard library or something you wrote…


What is a system() function?

system() is a predefined standard C/C++ library function. You can pass input commands such as “date” or “pause” to the system() function which will be executed on the operating system terminal.

Let’s first understand the syntax of the system() function

int system(const char *string);

int: int is the return type of system() function. If the command is executed successfully without any error returns 0 (zero). If any error occurs during function execution then it returns a non-zero value.

system: it is the name of a function.

Const char: You can pass any defined commands as a string to this function.

For example:

system(“date”): It returns and displays the current date from the system.

system(“mkdir  NewDirectory”): It creates a new folder with the name NewDirectory where the program is available

system(“cd”): It returns and displays the current directory path.

What is the use of a system(“pause”) function?

system pause c++ function

the system (“pause”) function is used to pause the program at any required stage or at the end of the program to check the output of the program on the console terminal.

Some IDE’s wait for the user’s inputs before closing the console window but in some IDE’s, it’s required to add a pause function explicitly so that the console window will wait for the user’s input before closing it.

system pause c++ function is generally used if the user wants to see the output results on the console window. It helps users to debug the program in a better way and users can see output values at different stages of the program.

Required header file to use system(“pause”) function:

To use the system function in your program, you must include the following header file at the beginning of the program.

#include <stdlib.h>

Example of using system(“pause”) function:

#include<iostream>
#include <stdlib.h>
using namespace std;
 
int main()
{
    int storedValues[5] = { 10, 20, 30, 40, 50 };
    
    for (int iCnt=0; iCnt<5; iCnt++) 
    { 
        if ( storedValues[iCnt]== 40) 
	{       
            cout << "Value 40 is available at array position: " << iCnt;
            // pause program
	    system("pause");
        }
    }
}

Disadvantages of the system(“pause”) function:

Dependent on the operating system:

Not all operating system supports system() function. It’s only supported on Windows or DOS operating systems. Linux and other operating systems do not support this function. If you want that your program can run on any operating system then using this function will give you errors on unsupported operating systems.

Resource Heavy function:

This is an operating system-level function. When you call this function, it passes commands to the operating system to pause the execution of the program. To simply pause the program execution, calling an operating system level function is not at all recommended. It’s like calling THOR to fit the fastener in the wall. If we can use any program-level function then that would be great.

Unnecessary header files:

To use the system function, you must include the stdlib.h or cstdlib.h header files at beginning of your program.

If you are not using any other functions from these header files apart from the system function then it’s unnecessary to add an entire header file just for a simple task. It will import all the functions available in these header files. It will unnecessarily increase the size of the dependent libraries.

Impacts program performance:

As it calls the operating system to execute the command and adds the entire header file for a simple function, it definitely impacts program performance. If the performance of a program is critical then you should not use this function. There are cheaper and easy alternate solutions are available to achieve the requirement. Keep reading.

Alternatives of the system(“pause”) function:

There are the following better alternatives available rather than using the system pause c++ function.

Use cin.get() function:

cin.get() is the best alternative for the system(“pause”) function. It will also stop the program execution at the required location. You can use cin.get() function as shown below.

#include<iostream>
using namespace std;
 
int main()
{
    int storedValues[5] = { 10, 20, 30, 40, 50 };
    
    for (int iCnt=0; iCnt<5; iCnt++) 
	{ 
        if ( storedValues[iCnt]== 40) 
		{       
            cout << "Value 40 is available at array position: " << iCnt;
            // pause the program to read output
	    cin.get();
        }
    }
}

cin.get() function stops the program execution and waits for input from the user before executing further. Once the user enters any value then program execution continues. This function can be useful if you want to pass any value to the program during execution.

cin.get() is a program-level function, it will not invoke the operating system to execute the command. system pause c++ is a standard library function hence there is no need to add a separate header file explicitly.

Note:  If you are using the C programing language then use getch() function to pause the program execution.

Add breakpoints in the code:

Adding a breakpoint in the program for debugging is the more preferred and efficient way to evaluate the program execution. If you just want to just debug the output of your program then you can use breakpoints. But this is possible only if you are using any IDE to debug the code. If you are not using any IDE and executing the code from the command line then the first approach is useful.

Also read…

How to call a java jar file from a C++ program using system() function.

Final thoughts:

So here we have understood the details about system function and more importantly about system pause c++ function. We hope this article was useful and you got clear about why we should not use the system(“pause”) function. Please let us know your experience and suggestions in the comment box or you can reach out to us using the contact form. We would be happy to hear from you.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Szone online steam ошибка
  • Systemsettingsbroker exe ошибка приложения