zoukankan      html  css  js  c++  java
  • about system (pause) in cpp

    Which is best way to pause the console in C++ programs?

    1. using cin.get()
    2. or using system("pause")
    3. or using C functions like getch() or getchar()?

    Is it true that use of system("pause") leads to non portable code and can't work in UNIX?

    Is cin.get() is better to use to pause console?

    在C和C++里,要尽量避免使用 system("pause")

    system("pause")

    I've never understood why system("PAUSE") is so popular. Sure it will pause a program before it exits. This pause is very useful when your IDE won't wait as you test a program and as soon as the program finished the window closes taking all your data with it.

    But using system("PAUSE") is like burning your furniture for heat when you have a perfectly good thermostat on the wall.

    Many people, instructors included, for some inexplicable reason think that making a call to the operating system and running a system command to temporarily halt a program is a good thing. Where they get this idea is beyond me. Reasons:

    • It's not portable. This works only on systems that have the PAUSE command at the system level, like DOS or Windows. But not Linux and most others...

    • It's a very expensive and resource heavy function call.

      It's like using a bulldozer to open your front door. It works, but the key is cleaner, easier, cheaper. What system() does is:
      1. suspend your program

      2. call the operating system

      3. open an operating system shell (relaunches the O/S in a sub-process)

      4. the O/S must now find the PAUSE command

      5. allocate the memory to execute the command

      6. execute the command and wait for a keystroke

      7. deallocate the memory

      8. exit the OS

      9. resume your program

      There are much cleaner ways included in the language itself that make all this unnessesary.

    • You must include a header you probably don't need: stdlib.h or cstdlib

    It's a bad habit you'll have to break eventually anyway.

    Instead, use the functions that are defined natively in C/C++ already. So what is it you're trying to do? Wait for a key to be pressed? Fine -- that's called input. So in C, usegetchar() instead. In C++, how about cin.get()? All you have to do is press RETURNand your program continues.

    Note: the origin of the article isn't specified.

    ++

  • 相关阅读:
    tornado开发学习之2.输入输出,数据库操作,内置模板,综合示例
    使用Python读取和写入mp3文件的id3v1信息
    在CentOS中部署Python和配置PyCharm开发环境
    Quartz Cron 表达式(时间格式的写法)
    使用Atomikos Transactions Essentials实现多数据源JTA分布式事务
    Grub4dos 硬盘引导 iso 文件
    NFS配置
    C++程序加载Flash动画
    在boost.foreach中操作迭代器
    WebContents类
  • 原文地址:https://www.cnblogs.com/loanhicks/p/6172143.html
Copyright © 2011-2022 走看看