C++ cin

cin

内容来自《C++ Primer》

cin使用>>运算符从输入流中抽取字符

bash 复制代码
    int carrots;
    cin >> carrots;

如下的例子,用户输入的字符串有空格

cpp 复制代码
#include <iostream>

int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize]; //用户名
    char dessert[ArSize]; //用户喜欢的甜点
    
    cout << "Enter your name:\n";
    cin >> name;
    
    cout << "Enter your favorite dessert:\n";
    cin >> dessert;
    
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    
    return 0;
}

如果用户输入steven jobs,如下:

cpp 复制代码
Enter your name:
steven jobs
Enter your favorite dessert:
I have some delicious jobs for you, steven.

可见,虽然本意是输入steven jobsname,但name却是steven,而dessert则为jobs

cin如何确定已完成字符输入?

使用空白(空格、制表符和换行符)来确定字符串的结束位置。

这意味着cin会读取一个单词,读取单词后,cin将字符串放到数组中,并自动在结尾处添加空字符

相关推荐
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss3 天前
BRpc使用
c++·rpc
-森屿安年-3 天前
63. 不同路径 II
c++·算法·动态规划