How to read multiple lines in c++ without using file

Asked

Viewed 379 times

-1

I need to make a program in c++ that reads a multi-line input and stores each line(string) in an array. I’ve tried using the cin.eof() and fgets() but it didn’t work.

#include<iostream> 
#include<string> 

using namespace std; 

int main()
{ 
    string entrada; 
    cin >> entrada; 
    while(!cin.eof())
    {
        cout << "Entrada ainda não terminou." << endl; 
        cin.ignore(); 
        getline(cin, entrada); 
        cout << entrada << endl; 
    } 

    cout << "Entrada terminou." << endl; 
    return 0; 
}

Anyone can help?

  • How’s the code you tried so far?

  • [#include<iostream> #include<string> using namespace Std; int main(){ string input; Cin >> input; while(!Cin.eof()){ Cout << "Input not finished yet." << Endl; Cin.ignore(); getline(Cin, input); Cout << input << Endl; } Cout << "Input finished." << Endl; ;}]

  • Is there any way to specify that my comment is a code? This is my first time doubting it here.

  • Usually editing your question. Here’s how I edited it. Four spaces in the front indicate to Markdown that it’s code.

  • Something else: Take a walk here, to understand how the site works.

  • I’ll look yes, thank you!

Show 1 more comment

1 answer

2


I changed your code a little bit to get a result inside of what I imagine you want to do:

#include<iostream> 
#include<string> 

using namespace std; 

int main()
{ 
    string entrada; 
    getline(cin, entrada); 
    cout << entrada << endl; 

    do
    {
        cout << "Entrada ainda não terminou." << endl; 
        // cin.ignore(); 
        getline(cin, entrada); 
        cout << entrada << endl;     
    } while(entrada != "");

    cout << "Entrada terminou." << endl; 
    return 0; 
}

See working here.

  • 1

    It was a little different than I thought it would work in the code, but I think it will work perfectly anyway. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.