Randy VU
Randy VU

Reputation: 109

Can you use "cin" with string?

I was taught that you have to use gets(str) to input a string and not cin. However I can use cin just fine in the program below. Can someone tell me if you can use cin or not. Sorry for my bad English. The program lets you insert 5 names and then print those names to the screen.

Here's the code:

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

int main()
{
    char **p = new char *[5];
    for (int i = 0; i < 5; i++)
    {
        *(p + i) = new char[255];
    } //make a 2 dimensional array of strings

    for (int i = 0; i < n; i++)
    {
        char n[255] = "";
        cout << "insert names: ";
        cin >> n; //how i can use cin here to insert the string to an array??
        strcpy(p[i], n);
    }

    for (int i = 0; i < n; i++)
    {
        cout << p[i] << endl; //print the names
    }
}

Upvotes: 6

Views: 40841

Answers (2)

Syed Nasir Abbas
Syed Nasir Abbas

Reputation: 1857

Use ws (whitespace) in getline() like getline(cin>>ws, name); If numeric input is before the string then due to whitespace the first string input will be ignored. Therefore use ws like getline(cin>>ws, name);

#include <iostream>
using namespace std;

main(){
    int id=0;   
    string name, address;

    cout <<"Id? "; cin>>id;

    cout <<"Name? ";
    getline(cin>>ws, name);

    cout <<"Address? ";
    getline(cin>>ws, address);

   cout <<"\nName: " <<name <<"\nAddress: " <<address;
}

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234635

You can indeed use something like

std::string name;
std::cin >> name;

but the reading from the stream will stop on the first white space, so a name of the form "Bathsheba Everdene" will stop just after "Bathsheba".

An alternative is

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

which will read the whole line.

This has advantages over using a char[] buffer, as you don't need to worry about the size of the buffer, and the std::string will take care of all the memory management for you.

Upvotes: 16

Related Questions