C库stdio.h和C++库iostream的getline的比较

文章对比了C++标准库中的getline函数在处理用户输入时,C风格和C++风格的差异,指出C++版省略了末尾的换行符。
摘要由CSDN通过智能技术生成

代码

#include <cstdlib>
#include <cstdio>

#include <string>
#include <iostream>

int main()
{
    size_t lineLen = 100;
    char *line = (char *)calloc(lineLen, sizeof(char));
    size_t size;
    /* input */
    /* hello world\n */
    size = getline(&line, &lineLen, stdin);
    printf("end of line is: %c, %u\n", line[11], line[11]);

    std::string str;
    /* input */
    /* hello world\n */
    std::getline(std::cin, str);
    /* \n is ignored */
    std::cout << str.at(str.size() - 1) << std::endl;
    // std::cout << str.at(11);/* error */
}

运行结果

hello world
end of line is: 
, 10
hello world
d

分析

两者的入参是不同的,详见其库函数说明;
C++版本的getline省略了末尾的换行符’\n’

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值