簡體   English   中英

在 C++ 中使用換行符中斷循環

[英]Using the newline character to break a loop in c++

我正在尋找一種在 Visual Studio 控制台中使用 enter 來中斷 for 循環的方法。

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

到目前為止,這是我所擁有的,但是換行符無法滿足我的需要,任何建議或見解都會有所幫助,謝謝!

PS 我不能使用除輸入按鈕產生的換行符以外的標記值。

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

默認情況下使用>>閱讀會跳過空格,換行符是空格。 我建議使用getline()代替:

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

如果您的lineStorage確實應該存儲單個單詞,則可以在存儲單詞之前將userInput拆分為空格。


編輯:既然您已經證明userInput是單個字符,我認為您應該只使用std::cin.get(userInput)讀取一個字符。 這將使您以原始代碼的樣式獲得換行符。

我更喜歡另一個答案,但這樣的事情也可以:

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

會更清楚

#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