2014-12-03 121 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; 
}