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
    }
}
2

2 Answers

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.

0

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest