2010-12-03 58 views
1

我剛開始學習C++。爲什麼跳出程序?

當我執行我的代碼時,它跳出程序沒有任何錯誤。爲什麼?

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

using namespace std; 

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

    char s1[20],s2[10]; 
    cout<<" enter a number : "; 
    cin.get(s1,19); 
    cout<<" enter a number : "; 
    cin.get(s2,9); 

    cout<<s1<<"/n"<<s2; 

    getch(); 

} 
+0

你的意思是「它跳出了程序」?你的意思是你不會輸入東西opn s1和s2? – Muggen 2010-12-03 15:13:34

+2

爲什麼你會首先使用微軟的優先級,C++的惡意擴展,比如「stdafx.h」和「_tmain」? – 2010-12-03 15:15:17

+1

夥計。你確定它編譯?它不適合VS2008。你對getch()包含什麼? – Muggen 2010-12-03 15:18:12

回答

6

get()方法讀取'\ n'字符,但不提取它。

所以,如果你輸入:122345<enter>
這條線:

cin.get(s1,19); 

會讀12345,但 '\ n'(通過敲擊<進入>創建)留在輸入流。因此,下一行改爲:

cin.get(s2,9); 

會讀什麼,因爲它看到了「\ n」和停止。但它也不提取'\ n'。所以輸入流在那裏仍然有'\ n'。所以這行:

getch(); 

只是從輸入流中讀取'\ n'字符。然後允許它完成處理並正常退出程序。

好的。這就是發生的事情。但還有更多。你不應該使用get()來讀取格式化的輸入。使用操作員>>將格式化的數據讀入正確的類型。

int main() 
{ 
    int x; 
    std::cin >> x; // Reads a number into x 
        // error if the input stream does not contain a number. 
} 

因爲給std :: cin是一個緩衝的流,直到你按下<進入>數據不會發送到程序和流被刷新。因此,一次讀取文本(來自用戶輸入)一行,然後獨立解析該行通常是有用的。這使您可以檢查上次用戶輸入的錯誤(如果有錯誤,則按行逐行排除)。

int main() 
{ 
    bool inputGood = false; 
    do 
    { 
     std::string line; 
     std::getline(std::cin, line); // Read a user line (throws away the '\n') 

     std::stringstream data(line); 
     int x; 
     data >> x;     // Reads an integer from your line. 
            // If the input is not a number then data is set 
            // into error mode (note the std::cin as in example 
            // one above). 
     inputGood = data.good(); 
    } 
    while(!inputGood); // Force user to do input again if there was an error. 

} 

如果你想先進的話,你也可以看看升壓庫。它們提供了一些不錯的代碼,作爲一個C++程序,您應該知道boost的內容。但是,我們可以在上面重新寫爲:

int main() 
{ 
    bool inputGood = false; 
    do 
    { 
     try 
     { 
      std::string line; 
      std::getline(std::cin, line); // Read a user line (throws away the '\n') 

      int x = boost::lexical_cast<int>(line); 
      inputGood = true;    // If we get here then lexical_cast worked. 
     } 
     catch(...) { /* Throw away the lexical_cast exception. Thus forcing a loop */ } 
    } 
    while(!inputGood); // Force user to do input again if there was an error. 

} 
1

您需要使用cin.ignore();獲得下一個輸入之前忽略流換行符。