为什么这个for循环不会中断

Dan*_*ims 1 c++ for-loop

我正在使用这个资源学习C++ http://www.learncpp.com/cpp-tutorial/58-break-and-continue/

我希望这个程序在输入命中空格后结束并打印空格类型的数量.相反,您可以根据需要输入任意数量的空格.当您按Enter键时,如果空格数超过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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 5

控制台输入是行缓冲的.在给出Enter之前,库不会向程序返回任何输入.如果你确实需要逐字符输入,你可能会发现绕过这个的操作系统调用,但如果你这样做,你会跳过有用的东西,比如退格处理.