可以在字符串中使用“ cin”吗?

问题描述

有人告诉我,您必须使用gets(str)输入一个字符串,而不是cin。但是,我可以在下面的程序中使用cin。有人可以告诉我您是否可以使用cin。对不起,我的英语不好。该程序允许您插入5个名称,然后将这些名称打印到屏幕上。

这是代码

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

解决方法

您确实可以使用类似的东西

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

但是从流中读取的内容将在第一个空白处停止,因此名称“ Bathsheba Everdene”的名称将在“ Bathsheba”之后停止。

一种替代方法是

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

它将读取整行。

与使用char[]缓冲区相比,这具有优势,因为您不必担心缓冲区的大小,std::string将为您处理所有内存管理。 / p>