从Stdin读取字符串

时间:2011-12-21 14:33:59

标签: c++ string stdin

我的代码从stdin读取到char*。是否可以直接在std::string

中执行此操作
int size = std::atoi(m_content_size);
char* buffer;
buffer = (char*)malloc(size);
fread(buffer, 1, size, stdin);

...

free(buffer);

我想我可以做std::string sBuffer(buffer),但我希望有更好的选择。

谢谢。

2 个答案:

答案 0 :(得分:3)

你应该阅读一个字符向量左右,只是为了不给你一个印象,如果你真的有任意二进制数据你有“文本”:

#include <iostream>
#include <vector>

// ...

std::vector<char> buf(size);
std::cin.read(buf.data(), buf.size());

// all done, will clean up after itself!

答案 1 :(得分:2)

int size = std::atoi(m_content_size);
std::string buffer(size);
fread(&buffer[0], 1, size, stdin);

虽然您可以使用cin(以及更合适的容器,如果它不是字符串而只是原始二进制数据)

相关问题