问题在接受C++中的字符串的空格
问题描述:
我写了这个代码来获取名称。电话和一个人的地址,然后我输入到这些类对象变量:问题在接受C++中的字符串的空格
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
using namespace std;
class contact{
public:
string name;//ALL CLASS VARIABLES ARE PUBLIC
unsigned int phonenumber;
string address;
contact(){//Constructor
name= "Noname";
phonenumber= 0;
address= "Noaddress";
}
/*void input_contact_name(string s){//function to take contact name
name=s;
}
void input_contact_number(int x){//function to take contact number
phonenumber=x;
}
void input_contact_address(string add){//function to take contact address
address=add;
}*/
};
int main(){
contact *d;
d= new contact[200];
string name,add;
int choice;//Variable for switch statement
unsigned int phno;
static int i=0;//i is declared as a static int variable
bool flag=false;
cout<<"\tWelcome to the phone Directory\n";//Welcome Message
cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Delete an Existing Entry\n4.Display All Contacts\n5.Search for a contact\n6.Exit PhoneBook\n\n\n";//Display all options
cin>>choice;//Input Choice from user
while(!flag){//While Loop Starts
switch(choice){//Switch Loop Starts
case 1:
cout<<"\nEnter The Name\n";
cin>>name;
d[i].name=name;
cout<<"\nEnter the Phone Number\n";
cin>>phno;
d[i].phonenumber=phno;
cout<<"\nEnter the address\n";
cin>>add;
d[i].address=add;
i++;
flag=true;
}
}
return 0;
}
但是如果我进入其姓分离的名称,代码绕过下一CINS并退出。有人能帮我解释为什么会发生这种情况吗? 当我输入10位数字单元号时,会发生同样的情况。 在此先感谢
答
使用std::getline()
而不是operator>>
来提取包含空格的std::string
。
+0
我想知道运算符>>和带空格的字符串是什么问题? – 2011-04-15 10:23:08
+3
'operator >>'读取一个元素。通常情况下,一个元素被认为是由下一个空白字符来终止,就像std :: string和所有基元一样。正如答案所说,“std :: getline”是你的朋友。 – Mephane 2011-04-15 11:02:10
请付出一些努力来格式化您的代码。发布较短的样本也是一个好主意。 – Mat 2011-04-15 10:09:26
谢谢你,我会在将来记住这一点:D – 2011-04-15 10:13:45
我建议你接受ildjarn给出的答案。已经有一段时间了,这是正确的答案。 – Mephane 2011-06-08 07:42:47