treeTallAsian
treeTallAsian

Reputation: 33

Using the newline character to break a loop in c++

I'm looking for a way to break a for loop using enter in the visual studio console.

do {
    std::cin >> userInput;
    if (userInput == '\n')
        break;
    lineStorage[lineLength] = userInput;
    lineLength++;
} while(true);

This is what I have so far, but the newline character won't work for what I need it to. Any suggestions or insight would help.

P.S. I cannot use a sentinel value other than the newline character resulting from the enter button.

P.S. More context:

char lineStorage[80] = { 'a' };
char userInput = ' ';
const char lineEnd = '\n';

int lineLength = 0;

std::cout << "Enter a line:";

do {
    std::cin >> userInput;
    if (userInput == '\n')
        break;
    lineStorage[lineLength] = userInput;
    lineLength++;
} while (true);

Upvotes: 3

Views: 1398

Answers (3)

ocrdu
ocrdu

Reputation: 2183

I like the other answer better, but something like this should also work:

do {
  cin.get(userInput);
  if (userInput == 10) {
    break;
  } else { 
    lineStorage[lineLength] = userInput;
    lineLength++;
  }
} while (true);

Upvotes: 1

more clear will be

#include <stdio.h>
#include <stddef.h>

int main(int argc , char *argv[])
{
    char t[70]={0},x;
    while(1)
    {
        scanf("%[^ ^\n]%c",t ,&x);
        if(x == '\n') break;
    }
}

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249133

Reading with >> by default skips whitespace, and a newline is whitespace. I suggest using getline() instead:

for(int i = 0; i < 80; i++) {
    if (!getline(std::cin, userInput) || userInput.empty())
        break;
    lineStorage[lineLength] = userInput;
    lineLength++;
}

If your lineStorage is really supposed to store individual words, you can split userInput on spaces before storing the words.


Edit: now that you've shown that userInput is a single character, I think you should just use std::cin.get(userInput) to read one character at a time. That will let you get the newlines in the style of your original code.

Upvotes: 3

Related Questions