你能在string中使用"cin"吗?

4
我曾经学过,输入字符串必须使用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
    }
}

你试过由名字和姓氏组成的名称吗?例如,“Peter Fish”这样的? - 463035818_is_not_an_ai
2
不要使用gets,它是一个已弃用的函数,而且有充分的理由:"该函数无法防止目标数组的缓冲区溢出,即使输入字符串足够长。在C++11中,std::gets被弃用,并在C++14中被移除。可以使用std::fgets代替。" - anastaciu
2个回答

12

您确实可以使用类似于

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

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

另一种选择是

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

这将读取整行。

与使用char[]缓冲区相比,这具有优点,因为您不需要担心缓冲区的大小,而且std::string会为您处理所有的内存管理。


3

在使用getline()函数时,可以通过添加ws(空格)来忽略之前的空白字符,例如:getline(cin>>ws, name)。如果在字符串之前有数字输入,则由于空格,第一个字符串输入将被忽略。因此,请像这样使用ws: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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接