2014-12-03 120 views
1

我學習C++使用這個資源http://www.learncpp.com/cpp-tutorial/58-break-and-continue/爲什麼for循環不打破

我希望這個節目結束並打印空間類型的數量被輸入命中空間之後。相反,您可以根據需要輸入儘可能多的空格。當您按回車鍵時,如果空格數超過5,程序將打印1,2,3,4或5.

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

int main() 
{ 
    //count how many spaces the user has entered 
    int nSpaceCount = 0; 
    // loop 5 times 
    for (int nCount=0; nCount <5; nCount++) 
    { 
     char chChar = getchar(); // read a char from user 

     // exit loop is user hits enter 
     if (chChar == '\n') 
      break; 
     // increment count if user entered a space 
     if (chChar == ' ') 
      nSpaceCount++; 
    } 

    std::cout << "You typed " << nSpaceCount << " spaces" << std::endl; 
    std::cin.clear(); 
    std::cin.ignore(255, '/n'); 
    std::cin.get(); 
    return 0; 
} 

回答

5

控制檯輸入是行緩衝的。該庫不會返回任何輸入到程序,直到給出回車。如果你真的需要逐字輸入的話,你可能會發現操作系統調用繞過了這一點,但如果你這樣做,你會跳過有用的東西,如退格處理。

+0

我現在明白了。該程序從用戶處獲取一個字符串,並逐字讀取,直到達到輸入符號或讀取了5個空格。我是小白。 – 2014-12-03 21:37:46

+0

@DanielSims,也許你是一個noob,但它根本不是一個愚蠢的問題。有時機罩下的機械裝置不明顯。 – 2014-12-03 21:42:33

2

爲什麼你有?

// loop 80 times 
for (int nCount=0; nCount <5; nCount++) 
{ 

} 

如果你只循環5次,這將是有道理的,你不能多加5個空格。也許你的意思

// loop 80 times 
for (int nCount=0; nCount <80; nCount++) 
{ 

} 

或者乾脆

while(true) 
{ 

} 
+0

不,我的意思是,在命中第5空間,程序應打印「您輸入的5位」。在我發佈代碼之前,我忘記了編輯該評論。 – 2014-12-03 21:26:01

1
std::cin.clear(); 
std::cin.ignore(255, '/n'); 
std::cin.get(); 

這三行不會讓你離開你的代碼,直到CIN停止忽略輸入。你把'/ n'倒過來,應該是'\ n'。

1

我替你寫的:

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

using namespace std; 

int main() 
{ 
    int intSpaceCounter = 0; 
    string strLine; 
    getline(cin,strLine); 
    for (int i = 0; i <= strLine.length(); ++i) 
    { 
     if (strLine[i] == ' ') 
     { 
      ++intSpaceCounter; 
     } 
    } 
    cout << "You typed " << intSpaceCounter << " spaces."; 
    return 0; 
}