std::string的输入

带有 std::cin 的字符串输入

#include <iostream>
#include <string>

int main()
{
    std::cout << "Enter your full name: ";//输入你的名字
    std::string name{};
    std::cin >> name; // this won't work as expected since std::cin breaks on whitespace

    std::cout << "Enter your age: ";
    std::string age{};
    std::cin >> age;//输入你的年龄

    std::cout << "Your name is " << name << " and your age is " << age << '\n';

    return 0;
}

​
运行结果

Enter your full name: John Doe
Enter your age: Your name is John and your age is Doe

      在这里遇到了和C语言中scanf("%s",s)中同样的问题,那就是一段字符串中如果有空格则会中断输入!

     c++的解决方案是使用”getline"读取一整行

          例如下面的代码要将整行输入读入字符串,最好使用该std::getline()函数。std::getline() 有两个参数:第一个是 std::cin,第二个是字符串变量。

#include <string> // For std::string and std::getline
#include <iostream>

int main()
{
    std::cout << "Enter your full name: ";
    std::string name{};
    std::getline(std::cin >> std::ws, name); // read a full line of text into name

    std::cout << "Enter your age: ";
    std::string age{};
    std::getline(std::cin >> std::ws, age); // read a full line of text into age

    std::cout << "Your name is " << name << " and your age is " << age << '\n';

    return 0;
}

运行结果如下 

Enter your full name: John Doe
Enter your age: 23
Your name is John Doe and your age is 23

     其中 std :: ws 是输入操作器,改变cin的输入方式——不再输入前导空格

更具体的在这位大佬总结的这里

C++输入/输出操作符简介_ガッシュ·ベル的博客-CSDN博客_c++输入运算符

本文大部分内容来自 www.learncpp.com 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值