Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use "cin" with string?

Tags:

c++

dev-c++

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
    }
}
like image 584
Randy VU Avatar asked Aug 24 '26 14:08

Randy VU


1 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.

like image 73
Bathsheba Avatar answered Aug 27 '26 03:08

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!