簡體   English   中英

用while循環讀取字符數據文件

[英]Reading file of character data with while loop

我有一個包含以下數據的文件:

1F B8 08 08 00 00 00 00

我正在將它讀入一個 int,將其轉換為一個字符,並將其存儲在一個數組中。

int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
   c = static_cast<unsigned char>(n);
   r[i++] = c;
}

工作正常。 如果數據中沒有空格,我該怎么做,即

1FB8080800000000

上面的代碼只是將 n 填充到 maxint 並退出。 我可以使用 getc 或類似方法創建一些東西,但我希望 C++ 代碼能夠處理這兩種情況。

您可以將數字作為字符串讀取並使用std::setw來限制讀取的字符數。 然后使用std::stoi轉換為整數:

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

將與空格分隔和非空格分隔的輸入一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM