栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

std::string的输入

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

std::string的输入

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

#include 
#include 

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  // For std::string and std::getline
#include 

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 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号