在輸入中存在空白行時如何在 C++ 中使用 getline()?


在 C++ 中,我們使用 getline() 函式從流中讀取行。它讀取輸入直到按下回車鍵或給出了指定的分隔符。在這裡我們將看到如何使用 getline() 函式將換行符作為輸入。讓我們看看以下實現以瞭解這個想法。

示例

 即時演示

#include<iostream>
using namespace std;
int main() {
   string str;
   int term = 4;
   while (term--) {
      getline(cin, str);
      while (str.length()==0 )
      getline(cin, str);
      cout << str << " : New Line" << endl;
   }
}

輸出

Hello
Hello : New Line
World
World : New Line
This is
This is : New Line
C++ Language
C++ Language : New Line

更新於:2019 年 12 月 17 日

845 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.