Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用while循环读取字符数据文件_C++_While Loop_Ifstream_Getc - Fatal编程技术网

C++ 使用while循环读取字符数据文件

C++ 使用while循环读取字符数据文件,c++,while-loop,ifstream,getc,C++,While Loop,Ifstream,Getc,我有一个包含以下数据的文件: 1F B8 08 08 00 00 我将其读入一个int,将其转换为一个字符,并将其存储在一个数组中 int n, i = 0; char c; while (ifs >> std::hex >> n) { c = static_cast<unsigned char>(n); r[i++] = c; } int n,i=0; 字符c; while(ifs>>std::hex>>n){ c=静态铸件(n); r[i++

我有一个包含以下数据的文件:

1F B8 08 08 00 00

我将其读入一个int,将其转换为一个字符,并将其存储在一个数组中

int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
   c = static_cast<unsigned char>(n);
   r[i++] = c;
}
int n,i=0;
字符c;
while(ifs>>std::hex>>n){
c=静态铸件(n);
r[i++]=c;
}
很好。如果数据中没有空白,即

1FB8080000000


上面的代码只是将n填充到maxint并退出。我可以使用GEC等来创建一些东西,但是我希望C++代码来处理这两种情况。

< P>你可以把这些数字当作字符串来读取,并用它来限制读取的字符数。然后使用转换为整数:

std::string ns;
while (ifs >> std::setw(2) >> ns) {
    r[i++] = static_cast<unsigned char>(std::stoi(ns, nullptr, 16));
}
std::string ns;
而(ifs>>std::setw(2)>>ns){
r[i++]=static_cast(std::stoi(ns,nullptr,16));
}

将同时使用空格分隔和非空格分隔的输入。

C++代码完全能够一次读取一个字符,如
getc
。你知道怎么做吗?我试着用
code
while(ifs>>std::setw(2)>>std::hex>>I)
code
其中我是一个整数。返回0x7FFFFFFF。我想避免所有的弦乐/演员表演。为什么该代码不返回十六进制字符?