KAPIL
KAPIL

Reputation: 3

taking strings with whitespaces in c++

#include<iostream>
using namespace std;
int main()
{
string p;
int n,i;
cin>>n;
for(i=1;i<=n;i++)
{
    cin>>p;
    cout<<p<<"\n";
}
return 0;
}

hiii.. i wanna take two strings and then print them one by one as in prog. but when i take n=2 and input the string "I wanna go"
it gives the output :

i
wanna

and it didn't ask me for second string.it is taking the string until it gets a whitespace.what should i do to resolve this?

Upvotes: 0

Views: 98

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

Instead of operator >> you should use function std::getline. For example

#include <iostream>
#include <limits>

int main()
{
   int n;

   std::cin >> n;

   std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
   // or simply std::cin.ignore();

   for ( int i = 1; i <= n; i++ )
   {
      std::string p;
      std::getline( std::cin, p );
      std::cout << p << "\n";
   }

   return 0;
}

Upvotes: 0

M2tM
M2tM

Reputation: 4505

Consider using std::getline.

std::string name;
std::getline(std::cin, name);

The above example is summarized from: std::cin input with spaces?

Upvotes: 1

Christos
Christos

Reputation: 53958

You have to change the initial value of your iteration variable i in you for statement to the following one:

for(i=0;i<=n;i++)

Upvotes: 2

Related Questions