代码
#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’