我如何编写此代码,以便它将“空格”作为地址的一部分?

问题描述

在这里,我编写了一个将地址作为用户输入的代码,但是当用户在地址之间输入“空格”时,编译器会将下一个单词作为下一个输入。我如何编写它,以便它将“空格”作为地址的一部分。 注意:我必须使用构造函数执行此操作,并且仅复制构造函数

#include<iostream>
#include<string.h>
using namespace std;
class address{
    string add;
    public:
    address(){
        cout << "Enter your current address"<<endl;
        cin >> add;

    }
    address(const address &ad1){
      add=ad1.add ;
      cout << "Permanent add: "<<add;

    }
};
int main(){
    char c;
    string add2;
    address ad1;
    cout << "Is your permanent address same as current address? y for yes" <<endl;
    cin >> c;
    if(c=='y'||c=='Y')
    {
      address ad2=ad1;
    }
    else{
        cout << "Enter your permanent address"<<endl;
        cin >> add2;
    }

}

解决方法

您应该改用std::getline

即替换

address() {
    cout << "Enter your current address"<<endl;
    cin >> add;    
}

使用

address() {
    cout << "Enter your current address" << endl;
    getline(cin,add);    
}

,然后在需要时执行新操作。