Home > Software engineering >  Why doesn't string class take in two words separated with space?
Why doesn't string class take in two words separated with space?

Time:11-17

I want to take in persons name using string object. But in my code if I put two part name separated with a space, only first part is displayed. My understanding is .c_str() returns a pointer to stored string with terminal null. Why is there a problem with space. I'm new to C and using Code::Blocks 13.12. This is a simplified version of the problem that I have in another program that I wrote. Thanks in advance.

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>


using namespace std;

int main()
{
   string sCusName;

   cout << "Please enter your name-> ";
   cin >> sCusName;


   int xsize = sCusName.length();
   char *tempBuffer = new char[xsize 1];

   strncpy(tempBuffer, sCusName.c_str(),xsize 1);

   cout << tempBuffer << " is a beautiful name." << endl;

   return 0;
}

When I enter single part name, program works fine. But if I put in two part name separated with space. Only first part is taken in.

CodePudding user response:

it is not possible to read multi-word string using cin rather you should use getline() the getline() function takes two arguments cin and string variable forexample:

   int main()
{
   string sCusName;

   cout << "Please enter your name-> ";
   getline(cin,sCusName);

   cout << sCusName << " is a beautiful name." << endl;

   return 0;
}
  • Related