注册 登录
编程论坛 C++教室

求教,为什么字符串变量遇到空格中断输出?如何解决?

日寂 发布于 2014-04-05 15:49, 744 次点击
程序代码:
//输入部分:
cout<<"address:";
cin>>addr;
//输出部分:
cout<<"address:"<<addr<<endl;
//情况:
//input:Shanghai Road
//output:Shanghai


[ 本帖最后由 日寂 于 2014-4-5 16:09 编辑 ]
4 回复
#2
rjsp2014-04-05 18:15
string  addr;
getline( cin, addr );
#3
日寂2014-04-05 18:40
回复 2楼 rjsp
程序代码:
#include<iostream>
#include<string>
using namespace std;
class Student
{
    protected:
        int num;
        string name;
        char sex;
    public:
        void set()
        {
            cout<<"num:";
            cin>>num;
            cout<<"name:";
            cin>>name;
            cout<<"sex:";
            cin>>sex;
        }
        void display()
        {
            cout<<"num:"<<num<<endl;
            cout<<"name:"<<name<<endl;
            cout<<"sex:"<<sex<<endl;
        }
        ~Student(){};
};
class Student1:public Student
{
private:
    int age;
    string addr;
public:
    void set_1()
    {
        set();
        cout<<"age:";
        cin>>age;
        cout<<"address:";//调用set_1时运行到这里停止
        getline(cin,addr);
    }
    void display_1()
    {
        display();
        cout<<"age:"<<age<<endl;
        cout<<"address:"<<addr<<endl;
    }
    ~Student1(){}
};
int main()
{
    Student1 s;
    s.set_1();//在输出"address:"后开始执行接下来的语句
    putchar(10);
    s.display_1();
    return 0;
}
#4
rjsp2014-04-08 08:26
回复 3楼 日寂
不知道你在说什么

cin>>age;
cout<<"address:";//调用set_1时运行到这里停止
cin>>ws;
getline(cin,addr);
#5
hubinyes2014-04-08 11:15
回复 4楼 rjsp
ws怎么用。。
1