你可以将“cin”与字符串一起使用吗?

Ran*_* VU 5 c++ dev-c++

我被告知你必须使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 13

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

std::string name;
std::cin >> name;
Run Code Online (Sandbox Code Playgroud)

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

另一种选择是

std::string name;
std::getline(std::cin, name);
Run Code Online (Sandbox Code Playgroud)

这将读取整行。

这比使用char[]缓冲区有优势,因为您无需担心缓冲区的大小,并且它将std::string为您处理所有内存管理。


Sye*_*bas 5

在 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;
}
Run Code Online (Sandbox Code Playgroud)