System pause c ошибка

Ronaldoo

6 / 5 / 2

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

Сообщений: 136

1

28.11.2013, 13:09. Показов 3238. Ответов 8

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


Студворк — интернет-сервис помощи студентам

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#define MAX 100
#define LEN 255
char text[MAX][LEN];
 
/* ïðîñòåéøèé òåêñòîâûé ðåäàêòîð */
int main(void)
{
register int t, i, j;
for (t=0; t<MAX; t++)
{
printf ("%d: ", t);
gets(text [t]);
if(!*text [t]) break; /* âûõîä ïî ïóñòîé ñòðîêå */
}
 
/* ïîñèìâîëüíûé âûâîä òåêñòà */
for (i=0; i<t; i++) {
for(j=0; text[i][j]; j++) printf("%ñ", text[i][j]);
printf ("%ñ", 'n');
}
 system("pause");
return 0;
}



0



244 / 155 / 48

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

Сообщений: 317

28.11.2013, 13:15

2

Подключите библиотеку stdlib.h или iostream.



1



6 / 5 / 2

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

Сообщений: 136

28.11.2013, 13:29

 [ТС]

3

Alex566, спасибо работает))))



0



:)

Эксперт С++

4773 / 3267 / 497

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

Сообщений: 9,046

28.11.2013, 14:09

4

Цитата
Сообщение от Alex566
Посмотреть сообщение

stdlib.h или iostream.

iostream тут не причем. <cstdlib>



1



5496 / 4891 / 831

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

Сообщений: 13,587

28.11.2013, 14:49

5

Цитата
Сообщение от Tulosba
Посмотреть сообщение

iostream тут не причем

В студии при чём.



0



:)

Эксперт С++

4773 / 3267 / 497

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

Сообщений: 9,046

28.11.2013, 14:54

6

alsav22, опираться надо на стандарт всё же. А какой хедер кого включает — это всё от лукавого.



0



Неэпический

17815 / 10586 / 2044

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

Сообщений: 26,627

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

28.11.2013, 16:04

7

Цитата
Сообщение от alsav22
Посмотреть сообщение

В студии при чём.

тогда уж сразу windows.h пихать надо



0



alsav22

28.11.2013, 16:15

Не по теме:

Цитата
Сообщение от Tulosba
Посмотреть сообщение

опираться надо на стандарт всё же. А какой хедер кого включает — это всё от лукавого.

Согласен, сам даже в студии пишу и #include <cstdlib>, и #include <iostream> (за что, бывает, подвергаюсь критике), но, с фактом не поспоришь: в студии достаточно #include <iostream>.

Цитата
Сообщение от Croessmah
Посмотреть сообщение

тогда уж сразу windows.h пихать надо

Лень искать тему (но точно помню — было, что удивило), где вы писали, что в студии, для того чтобы работал system(«pause»), достаточно #include <iostream>.



0



Croessmah

28.11.2013, 16:20


    Почемо выдает ошибку в строке system(«pause»)

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

где вы писали, что в студии, для того чтобы работал system(«pause»), достаточно #include <iostream>

эт я разбирался тогда с заголовками как раз :D



0



Here’s a question that I don’t quite understand:

The command, system("pause"); is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees.

Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it.

I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don’t understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all?

What are your thoughts on this subject?

Paul's user avatar

Paul

139k27 gold badges274 silver badges264 bronze badges

asked Jul 10, 2009 at 4:32

Faken's user avatar

3

It’s frowned upon because it’s a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS — the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn’t get to see the output of his new program.

Bodging in system("pause") runs the Windows command-line «pause» command and waits for that to terminate before it continues execution of the program — the console window stays open so you can read the output.

A better idea would be to put a breakpoint at the end and debug it, but that again has problems.

user3840170's user avatar

user3840170

26.4k4 gold badges28 silver badges61 bronze badges

answered Jul 10, 2009 at 4:36

ravuya's user avatar

ravuyaravuya

8,5364 gold badges30 silver badges33 bronze badges

4

It’s slow. It’s platform dependent. It’s insecure.

First: What it does. Calling «system» is literally like typing a command into the windows command prompt. There is a ton of setup and teardown for your application to make such a call — and the overhead is simply ridiculous.

What if a program called «pause» was placed into the user’s PATH? Just calling system(«pause») only guarantees that a program called «pause» is executed (hope that you don’t have your executable named «pause»!)

Simply write your own «Pause()» function that uses _getch. OK, sure, _getch is platform dependent as well (note: it’s defined in «conio.h») — but it’s much nicer than system() if you are developing on Windows and it has the same effect (though it is your responsibility to provide the text with cout or so).

Basically: why introduce so many potential problems when you can simply add two lines of code and one include and get a much more flexible mechanism?

Jonathan Leffler's user avatar

answered Jul 10, 2009 at 4:38

9

  • slow: it has to jump through lots of
    unnecessary Windows code and a
    separate program for a simple
    operation
  • not portable: dependent on
    the pause command
  • not good style:
    making a system call should only be
    done when really necessary
  • more
    typing: system("pause") is longer
    than getchar()

a simple getchar() should do just fine.

user3840170's user avatar

user3840170

26.4k4 gold badges28 silver badges61 bronze badges

answered Jul 10, 2009 at 5:02

Gavin H's user avatar

Gavin HGavin H

10.2k2 gold badges35 silver badges42 bronze badges

1

Using system("pause"); is Ungood Practice™ because

  • It’s completely unnecessary.
    To keep the program’s console window open at the end when you run it from Visual Studio, use Ctrl+F5 to run it without debugging, or else place a breakpoint at the last right brace } of main. So, no problem in Visual Studio. And of course no problem at all when you run it from the command line.

  • It’s problematic & annoying
    when you run the program from the command line. For interactive execution you have to press a key at the end to no purpose whatsoever. And for use in automation of some task that pause is very much undesired!

  • It’s not portable.
    Unix-land has no standard pause command.

The pause command is an internal cmd.exe command and can’t be overridden, as is erroneously claimed in at least one other answer. I.e. it’s not a security risk, and the claim that AV programs diagnose it as such is as dubious as the claim of overriding the command (after all, a C++ program invoking system is in position to do itself all that the command interpreter can do, and more). Also, while this way of pausing is extremely inefficient by the usual standards of C++ programming, that doesn’t matter at all at the end of a novice’s program.

So, the claims in the horde of answers before this are not correct, and the main reason you shouldn’t use system("pause") or any other wait command at the end of your main, is the first point above: it’s completely unnecessary, it serves absolutely no purpose, it’s just very silly.

answered Dec 30, 2015 at 2:39

Cheers and hth. - Alf's user avatar

6

In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System(«PAUSE») because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.

Further explanation in this article.

answered Jul 10, 2009 at 4:35

John T's user avatar

John TJohn T

23.6k11 gold badges56 silver badges82 bronze badges

4

You can use std::cin.get() from iostream:

#include <iostream> // std::cout, std::cin
using namespace std;

int main() {
   do {
     cout << 'n' << "Press the Enter key to continue.";
   } while (cin.get() != 'n');

   return 0;
}

Besides, system('pause') is slow, and includes a file you probably don’t need: stdlib.h. It is platform-dependent, and actually calls up a ‘virtual’ OS.

Dorian's user avatar

Dorian

22.5k8 gold badges119 silver badges116 bronze badges

answered Jul 15, 2013 at 23:51

Gavriel Feria's user avatar

3

Because it is not portable.
pause command is a windows / dos only program, so this your code won’t run on linux/macOS. Moreover, system is not generally regarded as a very good way to call another program — it is usually better to use CreateProcess or fork or something similar.

Felierix's user avatar

Felierix

1792 silver badges12 bronze badges

answered Jul 10, 2009 at 4:38

a_m0d's user avatar

a_m0da_m0d

12k15 gold badges57 silver badges79 bronze badges

As listed on the other answers, there are many reasons you can find to avoid this. It all boils down to one reason that makes the rest moot. The System() function is inherently insecure/untrusted, and should not be introduced into a program unless necessary.

For a student assignment, this condition was never met, and for this reason I would fail an assignment without even running the program if a call to this method was present. (This was made clear from the start.)

tshepang's user avatar

tshepang

12k21 gold badges91 silver badges135 bronze badges

answered Jun 7, 2010 at 15:00

Sam Harwell's user avatar

Sam HarwellSam Harwell

97.3k20 gold badges208 silver badges279 bronze badges

For me it doesn’t make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.

One also doesn’t silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.

answered Feb 7, 2013 at 20:12

Sebastian Mach's user avatar

Sebastian MachSebastian Mach

38.5k8 gold badges93 silver badges130 bronze badges

10

system("pause");  

is wrong because it’s part of Windows API and so it won’t work in other operation systems.

You should try to use just objects from C++ standard library. A better solution will be to write:

cin.get();
return 0;

But it will also cause problems if you have other cins in your code. Because after each cin, you’ll tap an Enter or n which is a white space character. cin ignores this character and leaves it in the buffer zone but cin.get(), gets this remained character. So the control of the program reaches the line return 0 and the console gets closed before letting you see the results.
To solve this, we write the code as follows:

cin.ignore();  
cin.get();  
return 0;

answered May 25, 2019 at 16:23

Sepideh Abadpour's user avatar

Sepideh AbadpourSepideh Abadpour

2,53010 gold badges51 silver badges88 bronze badges

3

It doesn’t matter.

Adding a system("pause") or getchar() or std::cin.get() or whatever else you like at the end of a console program is there solely for the benefit of the programmer during development. The only purpose of such a line is to ensure that the console won’t close before the programmer can view it, when executing the program from inside some IDE that likes to close the console when done executing.

That line will never make it to the production code executable, because why would anyone add «press any key to continue» at the end of a program executed from a console? That’s not how sane console program UI works and they never have.

In general, using system() is bad practice but that’s another story.

answered Aug 19, 2022 at 13:53

Lundin's user avatar

LundinLundin

192k39 gold badges251 silver badges392 bronze badges

Here’s one reason you shouldn’t use it: it’s going to piss off most anti-virus programs running on Windows if you’re passing the program over to another machine because it’s a security threat. Even if your program only consists of a simple cout << "hello worldn"; system("pause");
It’s resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.

answered Nov 27, 2014 at 20:48

Andreas DM's user avatar

Andreas DMAndreas DM

10.6k6 gold badges34 silver badges61 bronze badges

the pro’s to using system(«PAUSE»); while creating the small portions of your program is for debugging it yourself. if you use it to get results of variables before during and after each process you are using to assure that they are working properly.

After testing and moving it into full swing with the rest of the solution you should remove these lines. it is really good when testing an user-defined algorithm and assuring that you are doing things in the proper order for results that you want.

In no means do you want to use this in an application after you have tested it and assured that it is working properly. However it does allow you to keep track of everything that is going on as it happens. Don’t use it for End-User apps at all.

answered Oct 17, 2015 at 13:38

No one in particular's user avatar

1

Next to the arguments provided already (insecurity, slowness, non-portability, …) there’s yet another point missing:

If you are writing production tools of whatever kind then one should keep in mind:

  • Keeping an application window open is not the task of the application! Trying to do so by whatever means (system("pause");, getchar();, getch() or whatever else) is wrong by principle.
  • The application waiting for user input prevents it from being runable in any kind of scripting (bash script, windows batch file, …), which is a pretty common use case – who should provide the user input there?

These problems would already start if your teacher tried to automise testing your programme with different inputs in his own script (obviously it doesn’t…)!

Now if you are just playing around with any kind of testing code that you’ll throw away anyway without having been seen by anywhere else (including your teacher) – who should care? Problem then, though, is that you will get used to such practices and will tend to use them even in places where you shouldn’t. So best don’t get used to right from the start…

answered Jul 28, 2022 at 13:27

Aconcagua's user avatar

AconcaguaAconcagua

24.4k4 gold badges34 silver badges58 bronze badges

It’s all a matter of style. It’s useful for debugging but otherwise it shouldn’t be used in the final version of the program. It really doesn’t matter on the memory issue because I’m sure that those guys who invented the system(«pause») were anticipating that it’d be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn’t pose a direct threat like dynamic memory allocation, so I’d recommend it for debugging code, but nothing else.

answered Jul 11, 2011 at 6:50

Jason A.'s user avatar

Jason A.Jason A.

711 silver badge6 bronze badges

1

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

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.

5

Hi,

I can not get the system pause to work in a simple program. Here is my program below:

// i/o example

#include <iostream>
using namespace std;

int main ()
{
int i;
cout << «Please enter an integer value: «;
cin >> i;
cout << «The value you entered is » << i;
cout << » and its double is » << i*2 << «.n»;
system(«pause»);
return 0;
}

I get an implicit declaration of function ‘int system(…)’ error when I try to enter the pause code. I can not seem to get it to pause to program to see the results!! Please help

Jul 25 ’07
#1

  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…


Я делаю эту программу, где мне приходится использовать систему («пауза») несколько раз в Visual Studio, но всякий раз, когда я запускаю код, она вообще не останавливается. у меня есть <cstdlib> заголовок и все там. Есть ли еще одна причина, почему это не сработает? Спасибо!

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>using namespace std;

int main() {
int range = (rand() % 5) + 1;
double start = 0;
double end = 0;

cout << "Try to hit the same key within " << range << "seconds.";

system("pause");
start = clock();

system("pause");
end = clock();

system("pause");
return 0;
}

0

Решение

Это на самом деле хорошо работает для меня (в Windows), но если все, что вы хотите сделать, это прочитать нажатие клавиши, попробуйте это (должно работать везде):

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main() {
int range = (rand() % 5) + 1;
double start = 0;
double end = 0;

cout << "Try to hit the same key within " << range << "seconds.";

int c = getc (stdin);
start = clock();

c = getc (stdin);
end = clock();

c = getc (stdin);
return 0;
}

Живая демо

0

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

«Пауза» — это не программа, которую вы можете запустить сама по себе, это функция командной строки. Если вы должны сделать это с помощью системного вызова, вместо этого запустите:


cmd.exe /c pause

0


Recommended Answers

system(«PAUSE»);

This instructs your programme to ask the shell it is running inside to execute the command PAUSE, just as if you had typed PAUSE into a command line yourself. Your shell has no such command, and hence returns as error message. As I recall, this command commonly exists …

Jump to Post

You have to include windows.h, then system(«pause») or system(«PAUSE») will work fine. Here is a simple code I wrote to display the fact:

#include <windows.h>
int main()
{
    system("PAUSE");
    return 0;
}

Also although it is generally best to avoid OS specificity and keep C++ platform independant, …

Jump to Post

All 8 Replies

Member Avatar


Moschops

683



Practically a Master Poster



Featured Poster


12 Years Ago

system(«PAUSE»);

This instructs your programme to ask the shell it is running inside to execute the command PAUSE, just as if you had typed PAUSE into a command line yourself. Your shell has no such command, and hence returns as error message. As I recall, this command commonly exists in various Windows shells, but is not present in bash, csh, tcsh, fish and a number of other shells that are commonly used in *nix operating systems.

The solution is to step away from this hideous OS-dependent hack and do something actually within your programme if you want to pause the programme.

Edited

12 Years Ago
by Moschops because:

n/a

Member Avatar


Labdabeta

182



Posting Pro in Training



Featured Poster


12 Years Ago

You have to include windows.h, then system(«pause») or system(«PAUSE») will work fine. Here is a simple code I wrote to display the fact:

#include <windows.h>
int main()
{
    system("PAUSE");
    return 0;
}

Also although it is generally best to avoid OS specificity and keep C++ platform independant, sometimes it is more powerful to just use the system. (for example the horrible [in my opinion] language of VB is highly OS dependant on windows, yet it is an extremely powerful language that allows you to move windows through each other, and do hardware specific tasks. Though I still recommend using a platform independant method, or at least using a header check like #ifdef _WIN32 which checks if the system is windows 32 bit.

Edited

12 Years Ago
by Labdabeta because:

Footnote

Member Avatar


Moschops

683



Practically a Master Poster



Featured Poster


12 Years Ago

The system function actually lives in cstdlib; the problem is not that he doesn’t include system, as if that were the case, his code would simply not compile. The problem is not that system is unrecognised by the compiler; the problem is that his shell does not recognise the command PAUSE.

Member Avatar


WaltP

2,905



Posting Sage w/ dash of thyme



Team Colleague


12 Years Ago

Also although it is generally best to avoid OS specificity and keep C++ platform independant, sometimes it is more powerful to just use the system. (for example the horrible [in my opinion] language of VB is highly OS dependant on windows, yet it is an extremely powerful language that allows you to move windows through each other, and do hardware specific tasks.

Excuse me? VB isn’t «highly OS dependant on windows,» is was written completely dependent on Windows. Can you imagine having to write all the code necessary to create a form or a button from scratch so VB can be OS independent? Let alone the interrupt structure necessary to run the components! Very bad illustration.


@determine: See this

Edited

12 Years Ago
by WaltP because:

n/a

Member Avatar


Labdabeta

182



Posting Pro in Training



Featured Poster


12 Years Ago

I understand WaltP, VB is nearly completely for Windows (I actually wrote that, but changed it when I remembered that a friend of mine was able to get a simple program to work on his Linux computer) I should probably have used a better example, I am sorry *looks down in embarrassment*
Anyways, I was taught pseudocode a while ago for language and platform independant pauses, this syntax being:

Create a variable and set it to a value that is hard to enter (I usually use ‘a’ the alarm value)
While that variable is that value, ask the user to input that variable with no prompt.

The good thing about this is that it works even if input times out (like if you are using SDL_Event and SDL_PollEvent instead of SDL_WaitEvent)

Basic point is, the website that WaltP linked to seems to be good as far as I can tell, and if you need to pause in another circumstance or language than try a looping input.

Member Avatar


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster


12 Years Ago

>>You have to include windows.h,

No you don’t. including windows.h will make a simple console program carray around a lot of useless and unnecessary bagage. Just include cstdlib (as previously mentioned) or stdlib.h.

Member Avatar


Labdabeta

182



Posting Pro in Training



Featured Poster


12 Years Ago

Ok, ok, you win you’re right.

Member Avatar

12 Years Ago

>>You have to include windows.h,

No you don’t. including windows.h will make a simple console program carray around a lot of useless and unnecessary bagage. Just include cstdlib (as previously mentioned) or stdlib.h.

But can I do that on a OS with a Mac? I’m trying it now and it is not working.

EDIT: I just ended up deleting the line.

Edited

12 Years Ago
by determine because:

n/a


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • System net webexception удаленный сервер возвратил ошибку 500
  • System launcher ошибка загрузки xiaomi
  • System information ошибка
  • Tabletop simulator ошибка при запуске
  • Tabletop simulator ошибка при загрузке текстур