简体   繁体   English

在 C++ 中使用换行符中断循环

[英]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.我正在寻找一种在 Visual Studio 控制台中使用 enter 来中断 for 循环的方法。

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, thanks!到目前为止,这是我所拥有的,但是换行符无法满足我的需要,任何建议或见解都会有所帮助,谢谢!

PS I cannot use a sentinel value other than the newline character resulting from the enter button. PS 我不能使用除输入按钮产生的换行符以外的标记值。

PS More context: PS 更多上下文:

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);

Reading with >> by default skips whitespace, and a newline is whitespace.默认情况下使用>>阅读会跳过空格,换行符是空格。 I suggest using getline() instead:我建议使用getline()代替:

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.如果您的lineStorage确实应该存储单个单词,则可以在存储单词之前将userInput拆分为空格。


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.编辑:既然您已经证明userInput是单个字符,我认为您应该只使用std::cin.get(userInput)读取一个字符。 That will let you get the newlines in the style of your original code.这将使您以原始代码的样式获得换行符。

I like the other answer better, but something like this could also work:我更喜欢另一个答案,但这样的事情也可以:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM