2011-11-10 152 views
0

我建立一个控制台应用程序,在C++中,我想有两件事情:当用户在C++控制台应用程序中输入“退出”时,如何退出应用程序?

  • 当有人输入单词“退出”,退出控制台,
  • 当有人输入“SHOWME”表现出我制作的字符串。

我试图让这个

#include "stdafx.h" 
#include <stdio.h> 
#include <iostream> 

using namespace std; 

    int answer; 
    cout << "What do you want to learn?" << endl; 
    cin << answer << endl; 
    if answer == "show" 
    cout << "You have been shown the light" << endl; 
    if answer == "exit" 
    exit.window 

这就是我想象中的代码是,但如果有人可以请帮助,我对我的第4个C++课。 在此先感谢。

+5

引用我认为你已经错过了前3周C++的经验教训。 –

+0

@KirilKirov:我在想(希望)这是为了伪代码。 –

+0

@BenVoigt - 我也希望如此,:) –

回答

1

你可以使用一个简单的循环,如本:

#include "stdafx.h" 
#include <stdio.h> 
#include <iostream> 
#include <string> 

using namespace std; 

int main() { 

    string answer = ""; 

while(answer != "exit") 
{ 
    cout << "What do you want to learn?"; 

    cin >> answer; 

    if (answer = "show") 

    cout << "You have been shown the light"; 
} 
return 0; 
} 

请记住,这是一个伪代码示例,您应该能够从这里继续,并使用大量的资源可以在线找到正确的语法来获得这个工作顺序。

这里有一个很好的网站在整个旅程学习C++

cplusplus

+2

哦,这是在'if'中恶意使用赋值。虽然没有更好的学习方式。 –

+0

这篇文章的目标是展示循环的实现,没有更多。我相信他会在进展中涵盖更多主题,但处理这个问题可能是最好的解决方案。 – NRS

3

最简单的方法是从mainreturn

0

您需要使用字符串作为答案,而不是整数。 cin运算符也是>>,而不是< <。

+0

是的,我只是写了这个伪代码诚实 – Sinner

0

喜欢的东西:

int main() 
{ 
    std::string answer; 
    std::cout << "What do you want to learn?" << std::endl; 
    cin >> answer; 

    if(answer == "show") 
    cout << "You have been shown the light" << endl; 
    if(answer == "exit") 
    return 0; 
} 
+0

我刚试过这一个,它给了我一个错误:(即时通讯使用视觉工作室2010年我也加上了这个包括 Sinner

+1

嗯,这个程序将退出,无论用户输入:) – jrok

4

这里有几点:

  • 你缺少的代码为您main功能。

  • 您正试图输出<<cin,而应该输入>>

  • 您正试图输入一个int它应该是string

  • 您的if语句缺少括号。

  • 要退出控制台,只需returnmain或致电exit(status)

+0

是啊我只是写了这个伪代码诚实没有看到它在那里我可以将来自cin的输入添加到字符串中,然后在if中使用该字符串作为ex。 (如果繁荣进入显示繁荣景气)?我仍然是一个在C++的初学者 – Sinner

+0

@Sinner:是的,你可以做任何你想要的字符串。 –