为什么这个循环不中断

Why does this for loop not break

本文关键字:中断 循环 为什么      更新时间:2023-10-16

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

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

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

你为什么有?

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

如果您只循环 5 次,则不能添加超过 5 个空格是有意义的。也许你的意思是

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

或者干脆

while(true)
{
}
std::cin.clear();
std::cin.ignore(255, '/n');
std::cin.get();

这三行将不允许您退出代码,直到 cin 停止忽略输入。你把"/n"颠倒过来,应该是""。

我为你写的:

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