LovelyWei's 废纸篓

A Noob.

LovelyWei's avatar LovelyWei

cpp学习笔记(scanf与getline)

蒟蒻萌新的 C 与 C++学习笔记.

任何一个伟大的目标,都有一个微不足道的开始. —— 洛谷

最近在学习一些 OI 的知识,其实以前是学过 C++的但是, Python 实在是太香了
由于太久没用过全部白给了,但是由于了解到比赛 C++可以用 STL 真香
所以开了一个从 C 转换到 C++的一些笔记. 天坑 > 什么时候支持 C++11

从 scanf 到 cin 到 getline

之前习惯使用 scanf 来某些格式化的输入 如
https://vjudge.net/problem/HDU-2005

可以通过

scanf("%d/%d/%d",&year,&month,&day);

分割输入

转换到 C++时 当然是要使用 STL 辣

但是似乎没有类似

cin>>year>>month>>day

的操作,后面找到了一个代替方案

std::getline()

getline 有四个重载 其中

template<class _Elem,
    class _Traits,
    class _Alloc> inline
    basic_istream<_Elem, _Traits>& getline(
        basic_istream<_Elem, _Traits>& _Istr,
        basic_string<_Elem, _Traits, _Alloc>& _Str,
        const _Elem _Delim)
        {
        // get characters into string, discard delimiter
        return (getline(_STD move(_Istr), _Str, _Delim);
        }

这个方法可以设置结束符号

还是与HDU-2005为例子

1985/1/20

    std::string year;
    std::string month;
    std::string day;
    while (std::getline(std::cin, year, '/'))
    {
        std::getline(std::cin, month, '/');
        std::getline(std::cin, day, '/');
    }

这样就可以获取到三个值了

总感觉有点怪怪的,应该有更好的方法我不知道吧,各位dalao评论区请

This blog is under a CC BY-NC-SA 3.0 Unported License
Link to this article: https://hex.moe/p/a8715418/