我正在用 C++ 编写霍夫曼代码,现在我正在从文件中获取数据,但遇到了一个障碍。第一行我有一串字符,我想将其作为字符串,我发现这一点也不难。但是我必须将接下来的 x 行数字作为无符号字符,这样我才能使用它们。
如果我想从文件中提取这个文件,我应该输入什么?
ILaILbILrILcLd(想作为一个字符串)
3(3是它下面#的个数)
89(想把这3个作为unsigned chars取出来
207
88
最佳答案
正如耐克告诉我们的那样,去做吧:
// read the line:
std::string line1;
std::getline(infile, line1);
// read the int:
int num;
infile >> num;
// probably want to sanity check `num` here
// define a place to store the chars
std::vector<char> chars;
// read the chars.
for (i=0; i<num; i++) {
unsigned int temp;
infile >> temp;
chars.push_back(static_cast<unsigned char>(temp));
}
在这种情况下它可能不会完成太多,但是在 chars
定义之后,您可以添加:chars.reserve(num);
以避免重新分配vector
的内存。
关于c++ - 如何从文件中收集不同的变量类型 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13860363/