cin>>string
takes input until space or new line. But getline(cin,string)
takes input until new line. Again, getline(cin,string,'c')
takes input until 'c'. Is there any way to ignore a few '\n'
character and take a specified number of lines as input?
I tried the code below but it didn't work
int main()
{
string a;
for(int i=0;i<4;i++)
{
getline(cin,a);//take string input
}
cout<<a;
}
here for the following input
ksafj kfaskjf(\n)1st
uuiiuo akjfksad(\n)2nd
ksafj kasfj(\n)3rd
asdfed kkkl(\n) when the 4th enter comes input terminate
string a
only holds "asdfed kkkl"
. I want it to hold all the characters, including the end-of-lines (\n
).
Do you want to get the first n lines?
std::string get_n_lines(std::istream& input, const std::size_t n)
{
std::ostringstream result;
std::string line;
std::size_t i = 0;
while (std::getline(input, line) && i < n)
{
result << line << '\n';
++i
}
return result.str();
}
std::string first_4_lines = get_n_lines(std::cin, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With