简体   繁体   中英

How do I stop reading a newline from a string?

I have to find a method which displays the 2nd line from a given text. If the text is less than two lines long then it should display "text not long enough". My initial solution was to use the getline() function twice, but the online evaluator refuses to pass one of the tests..

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

Can you spot the problem and suggest a solution, please?

What should line if(a.length()) accomplish? It just checks if the string a contains at least one character.

In pseudo-code you wrote:

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

That is because if length is 0 it translates to false , every other number is considered true .

As john wrote:

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

Which roughly translates to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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