[英]Reading file of character data with while loop
I have a file with data like:我有一个包含以下数据的文件:
1F B8 08 08 00 00 00 00 1F B8 08 08 00 00 00 00
I am reading it into an int, casting it to a character, and storing it in an array.我正在将它读入一个 int,将其转换为一个字符,并将其存储在一个数组中。
int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
c = static_cast<unsigned char>(n);
r[i++] = c;
}
works fine.工作正常。 How do I go about doing this if there is no white space in the data, ie
如果数据中没有空格,我该怎么做,即
1FB8080800000000 1FB8080800000000
The above code just fills n to maxint and exits.上面的代码只是将 n 填充到 maxint 并退出。 I can create something using getc or the like but I'd like the C++ code to handle both cases.
我可以使用 getc 或类似方法创建一些东西,但我希望 C++ 代码能够处理这两种情况。
You could read the numbers as strings and use std::setw
to limit the number of characters read.您可以将数字作为字符串读取并使用
std::setw
来限制读取的字符数。 Then use std::stoi
to convert to integers:然后使用
std::stoi
转换为整数:
std::string ns;
while (ifs >> std::setw(2) >> ns) {
r[i++] = static_cast<unsigned char>(std::stoi(ns, nullptr, 16));
}
Will work with both the space-delimited and non space-delimited input.将与空格分隔和非空格分隔的输入一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.