簡體   English   中英

如何停止從字符串中讀取換行符?

[英]How do I stop reading a newline from a string?

我必須找到一種方法來顯示給定文本的第二行。 如果文本長度少於兩行,則應顯示“文本不夠長”。 我最初的解決方案是使用getline() function 兩次,但在線評估員拒絕通過其中一項測試。

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    string a;
    getline(cin,a);
    getline(cin,a);
    if(a.length())
        cout << a;
    else
        cout << "text not long enough";
}

你能發現問題並提出解決方案嗎?

if(a.length())行應該完成什么? 它只是檢查字符串a是否包含至少一個字符。

在你寫的偽代碼中:

if a has at least one character then
    print a
else
    print "text not long enough"

那是因為如果 length 為 0 它會轉換為false ,那么每隔一個數字就會被認為是true

正如約翰所寫:

if (getline(cin, a) && getline(cin, a))
    cout << a;
else cout << "text not long enough";

這大致翻譯為:

bool isInputTwoLinesLong()
{
    int newlines = 0;
    char c;
    while(cin >> c)
    {
        if (c == '\n') newlines++;

        // input contains at least two lines
        if (newlines == 2) return true;
    }

    // input not long enough
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM