簡體   English   中英

將輸出獲取到C ++中的“控制台”窗口

[英]Get output to the Console window in C++

所以我是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的最后一個}上放置一個斷點,然后在調試器中運行它。

不是為“到此為止”的末尾加上一個好主意。


如果你想看到,因為它的生產輸出的每一行,只是放置一個斷點輸出語句之后,並在調試器中運行該程序,在Visual Studio按鍵F5。


順帶一提, <stdafx.h>不是一個標准的報頭。 它支持Visual C ++預編譯頭,該功能會產生非常不標准的預處理器行為。 最好在項目設置中將其關閉,然后刪除>stdafx.h>包含。


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

是一種愚蠢的非標准Microsoft-ism,一次支持Windows 9x,但除供應商鎖定之外,不再具有其他目的。

只需寫標准

int main()

或使用尾隨返回類型語法,

auto main() -> int

最后,代替

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

寫吧

counter%(primeCounter-1) != 0

cin.get()將做您想要的。

在Visual Studio中,您實際上可以調用system("pause"); 在需要暫停應用程序的地方。

所以我想出了我的問題。 首先,循環沒有運行,因為第一個if語句沒有循環。 我將其更改為一會兒,現在輸出就像一個超級按鈕。 看一看

#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;
}


}

現在,我只需要改善條件即可實際找出素數。 再次感謝你的幫助。!!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM