Daniel Sims
Daniel Sims

Reputation: 41

Why does this for loop not break

I'm learning C++ using this resource http://www.learncpp.com/cpp-tutorial/58-break-and-continue/

I expect this program to end and print the number of spaces types after hit spaces are entered. Instead, you can enter as many spaces as you want. When you hit enter, the program prints 1,2,3,4 or 5 if the number of spaces is over 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;
}

Upvotes: 1

Views: 108

Answers (4)

Arma
Arma

Reputation: 152

I wrote it for you:

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

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308111

Console input is line buffered. The library doesn't return any input to the program until the Enter is given. You can probably find OS calls that bypass this if you truly need character by character input, but if you do you'll skip useful things like backspace processing.

Upvotes: 5

user2970916
user2970916

Reputation: 1186

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

These three lines will not allow you to exit your code until cin stop ignoring input. You have the '/n' reversed, should be '\n'.

Upvotes: 1

marsh
marsh

Reputation: 2720

Why do you have?

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

}

If you are only looping 5 times it would make sense that you can not add more then 5 spaces. Perhaps you meant

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

}

or simply

while(true)
{

}

Upvotes: 2

Related Questions