You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何使用getline()将用户输入赋值给string指针?

解决string指针获取用户输入为空的问题

你的代码问题出在输入缓冲区的残留换行符:用cin >> phoneNum读取手机号时,只会读取到换行符前的内容,输入结束时敲的回车(换行符)会留在输入缓冲区里。接下来调用getline(cin, *name)时,getline会直接读取这个残留的换行符,认为输入结束,所以name拿到的是空字符串。

另外你尝试的第二种写法name = new string(getline(cin,*name));完全错误,因为getline返回的是std::istream&对象,没有对应的std::string构造函数能接收这个参数,编译阶段就会报错。

修正后的代码(保留string指针)

#include <iostream>
#include <string>
#include <cassert>
#include <limits>

UserInfo::UserInfo() 
{
    std::cout << "Please enter your PhoneNumber: ";
    std::cin >> phoneNum;
    // 清空缓冲区中所有残留字符,直到遇到换行符(包括换行符)
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Please enter your name: ";
    name = new std::string();
    std::getline(std::cin, *name);
    assert(name != nullptr);
}

更优方案:避免使用string指针

没必要用std::string*指针,直接用std::string成员变量更安全,还能避免内存泄漏风险:

#include <iostream>
#include <string>
#include <limits>

class UserInfo {
private:
    std::string name;
    std::string phoneNum; // 假设phoneNum是string类型成员
public:
    UserInfo() {
        std::cout << "Please enter your PhoneNumber: ";
        std::cin >> phoneNum;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::cout << "Please enter your name: ";
        std::getline(std::cin, name);
    }
};

内容的提问来源于stack exchange,提问作者Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:40:25