【问题标题】:how can i write this code so that it will accept "space" as a part of address?我该如何编写这段代码,以便它接受“空格”作为地址的一部分?
【发布时间】:2020-08-17 09:41:24
【问题描述】:

在这里,我编写了一个代码,用于将地址作为用户的输入,但是当用户在地址之间输入“空格”时,编译器将下一个单词作为下一个输入。我该如何编写它以便它将“空格”作为地址的一部分。 注意:我必须只使用构造函数和复制构造函数来做到这一点

#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;
    }

}

【问题讨论】:

  • 编译器与它无关。这是您的代码通过运行时库执行此操作的。

标签: c++ string constructor copy-constructor


【解决方案1】:

您应该改用std::getline。

即替换

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

与

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

然后在需要时执行相同的操作以获取新地址。

【讨论】:

  • @Nitin 如果它帮助并解决了您的问题,请将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多