Home > Blockchain >  How to print string in C using getline
How to print string in C using getline

Time:03-20

Why this doesn't print the first word of sentence?

#include <iostream>
#include <string>

int main()
{
    std::string sentence;
    std::cout<<"Enter sentence: ";
    std::cin>>sentence;
    std::getline(std::cin,sentence);
    std::cout<<sentence;
    return 0;
}

If I enter

"This is text"

output would be

" is text"

CodePudding user response:

You dont need the first cin (std::cin>>sentence;), this will solve your problem

#include <iostream>
#include <string>

int main()
{
    std::string sentence;
    std::cout<<"Enter sentence: ";
    std::getline(std::cin,sentence);
    std::cout<<sentence;

    return 0;
}

  • Related