用c++将输出输出到控制台窗口

Get output to the Console window in C++

本文关键字:输出 控制台 窗口 c++      更新时间:2023-10-16

所以我是c++的新手,我希望社区可以帮助我完成我的作业。现在我不要求别人为我做,因为我很有能力做我自己,我只是要求帮助在一个特定的部分。所以,我的任务是编写一个程序,能够找到并输出2到100之间的所有质数。我必须使用双循环(这是我的教授说的),所以我设置了一个if语句来运行从2到100的所有数字,并在第一个语句中有第二个循环来确定当前数字是否是素数,然后打印它。这就是我的问题发挥作用的地方,当我运行它时,它打开控制台窗口并关闭它如此之快,我无法看到是否有任何东西打印到它。所以我添加了一个断点来看看它是否可以。当我按下F5步进每个下一步,它通过循环运行一次,然后它开始跳转到不同的窗口阅读不同的源文件行(我认为它们是源文件)。最终,控制台窗口关闭,没有打印任何内容,并且它不会像它应该的那样重新开始循环。我的问题是这样的,就像在Visual Basic中,你可以把console.readline(),所以一个按钮必须从键盘上按下才能继续,你怎么能在c++中做同样的事情,这样在循环后,看看数字是否为素数运行并打印数字,程序将等待一个键被按下后,它被打印?

这是我现在的代码如下,再次感谢任何帮助,我真的很感激。

#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int counter=2;
int primeCounter=counter;
//two variables, one to keep track of the number we are one, the other to check to see if its prime.
if(counter<101)
{//I want the counter to increment by 1 everytime the loops runs until it gets to 100.
    if(!(counter%(primeCounter-1)==0))//if the counter has a remainer, then it is prime
    {//each time the main loop run i want this loop to run too so it can check if it is a prime number and then print it.
        cout<<counter<<endl;
    //if this was VB, here is where i would want to have my console.Readline()
    }
    else
    {
    }
    counter+=1;
}
else
{
}   

由于您使用的是Visual Studio,您可以使用Ctrl+F5来运行您的程序而无需调试。这样,程序结束后,控制台窗口将保留。

或者您可以从命令行运行程序。

或者您可以在main的最后一个}上放置一个断点,并在调试器中运行它。

不是添加“stop here”


如果你想看到每一行的输出,只需在输出语句后放置一个断点,然后在调试器中运行程序,在Visual Studio中按下F5


顺便说一句,<stdafx.h>不是标准标头。它支持Visual c++预编译头文件,这是一个产生相当非标准预处理器行为的特性。最好在项目设置中将其关闭,并删除>stdafx.h> include。


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

是一个愚蠢的非标准的微软符号,曾经用于支持Windows 9x,但现在除了厂商锁定之外没有其他用途了。

只写标准的

int main()

或带有尾随返回类型语法的

auto main() -> int

最后,代替

!(counter%(primeCounter-1)==0)

counter%(primeCounter-1) != 0

cin.get()将按您的要求执行

在Visual Studio中,你可以在需要挂起应用程序的地方调用system("pause");

所以我知道我的问题了。首先,循环没有运行,因为第一个if语句没有循环。我将其更改为a while,现在输出效果非常好。看一下

#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int counter=2;
int primeCounter=counter;
//two variables, one to keep track of the number we are one, the other to check to see if its prime.
while(counter<101)
{//I want the counter to increment by 1 everytime the loops runs until it gets to 100.
    if((counter%(primeCounter-1)==0))//if the counter has a remainer, then it is prime
    {//each time the main loop run i want this loop to run too so it can check if it is a prime number and then print it.

    }
    else
    {
        cout<<counter<<endl;
    }
    counter+=1;
    primeCounter=counter;
}

}

现在我只需要完善这个条件来求出质数。再次感谢您的帮助。!!!!