hkasera
hkasera

Reputation: 2148

Code for getting multiple words in a string from user

Actually i want the user to enter a line of string having multiple words in it for example "My name is ABC". What is the C/C++ code for this purpose?

Thanks in advance

Upvotes: 6

Views: 52231

Answers (5)

CodeRain
CodeRain

Reputation: 6582

You can use std::getline() to get a line from std::cin.

#include <iostream>
#include <string>
using namespace std;

int main () 
{
  string name;
  cout << "Enter Name: ";
  getline (cin,name);
  cout << "You entered: " << name;
  return 0;
}

Upvotes: 2

Chaitanya Shejwal
Chaitanya Shejwal

Reputation: 21

Following code will help you receive multiple names from user.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name[6];
    cout << "\nEnter your name : ";
    for(int i = 0; i < 6; i++)
    {
        getline(cin, name[i]);
    }
    for(int i = 0; i < 6; i++)
    {
        cout << "\nYou entered : " << name[i];
    }
    return 0;
}

Upvotes: 1

Richie Flores
Richie Flores

Reputation: 81

#include<iostream>
#include<string> 
using namespace std;

int main(){

string testString;
getline(cin, testString);

{

if you have

cin >> otherVariables

You need to delete the newline buffer in between by adding:

cin.ignore()

You should have something like:

string userMessage;
cin.ignore();
getline(cin, testString);

Upvotes: 8

wilhelmtell
wilhelmtell

Reputation: 58677

#include<string> and see std::getline().

Upvotes: 2

nybbler
nybbler

Reputation: 4841

Try using something like this snippet:

string testString;

getline(cin, testString);

Upvotes: 5

Related Questions