2016-07-05 56 views
0

我刚开始学习C++,我希望程序在显示结果后保持打开状态。所以我用getch();而C++则表明它应该有一个原型。这是什么意思?以及如何解决这一>getch()显示原型错误

+0

显示确切的错误。 –

+0

你确定它是'C++'而不是'c'吗? –

+0

是的,它是C++。 :) –

回答

1

就意味着下列条件之一:

  1. 你在DOS下编程,忘了包括CONIO.H(https://en.wikipedia.org/wiki/Conio.h)。可能你从旧教科书中复制了一个源文件,因为conio.h是一个非常古老的概念。你用什么来源学习?我推荐一个来自:The Definitive C++ Book Guide and List

  2. 你在Linux下编程,你忘了,包括curses.h(http://linux.die.net/man/3/getch

+0

你忘了Windows。 –

+1

@MichaelWalz我不认为任何(自我尊重)Windows编译器随conio.h一起发货。如果我没有记错的话,它是Borland的一个旧Turbo C头。 – fritzone

+0

conio.h仍然与我的Visual Studio 2013交付。 –

-1

如果您使用的是Windows然后getch是从Windows的功能只有<conio.h> library。您需要包含它(#include <conio.h>)。 只有在Windows上才有可能。

另外,getch()已弃用。 改为使用_getch()


如果你在GNU + Linux的,那么getch距离<curses.h> library的功能。你需要包括它(#include <curses.h>)。

0

包括:

1)<conio.h>在Windows上。

2)<curses.h>在UNIX

0

看起来你只是想PAUSE在屏幕上的控制台应用程序。使用此#include <stdio.h>并尝试getchar();而不是getch();或只需system("pause");cin.ignore()将为您完成这项工作。

此外,“不开始调试”用Ctrl-F5将让你按任意键在程序结束继续。这样,只有按下某个键后,控制台才会在显示屏上暂停。

+0

您没有添加“C++”解决方案:'cin.ignore()'。 – 2016-07-05 13:41:27

+0

@MatthewRoh你在这里:) –

+0

不错! :)现在它匹配C++标签。 – 2016-07-05 13:48:36

0

我的理解是客观的:

我想要显示的结果后

方案保持开放何乐而不为呢典型的c++方式?

#include<iostream> 

int main(void) 
{ 
    int i; 
    char ch; 
std::cout<<"Enter any character : "; 
std::cin.get(ch); // For testing enter a string at this step say "String" 

/* The input to cin is line-buffered, so after reading 'S' to ch, 
* the remaining "tring" is still in the buffer. 
*/ 

std::cout<<"Entered character : "<<ch<<"\n"; 
while(std::cin.get()!='\n') 
;; 
/* cin.get() is an overloaded function in the istream class. 
* If no arguments are passed to 'get()' this function reads single next character 
* In essence, we wait for the cin.get() to clear the buffer that is 
* read all characters including '\n' 
*/ 

std::cout<<"Press any key to continue..\n"; 
std::cin.get(); 
/* Since we have already cleared the buffer using the loop 
* 'get()' expects us to enter a character this time 
*/ 

return 0; 
} 
+0

为什么不使用'cin.ignore()'? – 2016-07-05 13:57:38

+0

@MatthewRoh:呃,我之前没有使用过这种方法。在阅读其他答案的评论之后,我正在阅读该手册。稍后会更新。 – sjsam

+1

@MthetheRRoh:我的第一印象是在这里使用cin.ignore()是一种奢侈。我可以用更容易理解的'while()'循环完成工作 – sjsam