您可以将"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";将在";巴斯谢巴";。

另一种选择是

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

它将读取整行。

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

在getline((中使用ws(空白(,类似于getline(cin>>ws,name(;如果数字输入在字符串之前,那么由于空白,第一个字符串输入将被忽略。因此,使用类似getline的ws(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;
}

相关内容

最新更新