![](/img/trans.png)
[英]How to get the strings from a file and store in a 2D char array and compare that 2D char array with a string in C?
[英]How to separate binary strings from text file and store them in 1d or 2d char array?
“ 01110011 01100001 01100100”這將是一行,其中8位由文件中的空格分隔。
目前我有:
if (fr != NULL) //see if file opens or not
{
char chter[500]; //char to get string from text
char *ptr; //pointer to char
//char store[100][32];
fgets(chter, 1000, fr); //gets text from file
printf("%s", chter); //prints current text to cmd from textfile
puts("\n");
for (int i = 0; i < 1; i++)
{
li1 = strtol(chter, &ptr, 2); //convert 1st binary set to alphabet
printf("%c", li1); //Not sure how to get the rest of the sets from here on
}
puts("\n");
fclose(fr);
}
我當時在考慮使用2d數組存儲多個字符串,但是我遇到了麻煩。 由於我不知道如何從另一個字符串中分別提取二進制位。
在每次調用strtol
, ptr
將指向字符串中不屬於解析整數的第一個字節。 這將是您下一次迭代的起點。 由於fgets
返回帶有換行符的字符串,因此請循環執行,直到ptr
指向換行符或字符串末尾的空字節為止。
char *ptr, *tmp;
tmp = chter;
do
{
li1 = strtol(tmp, &ptr, 2);
printf("%c", li1);
tmp = ptr;
} while ((*ptr != '\n') && (*ptr != '\0'));
您遇到的主要問題是無法為strtol (ptr, &endptr, 2)
使用單獨的指針strtol (ptr, &endptr, 2)
,這將使您無法使用chter
中chter
所有值。 其次,通過潛在地閱讀1000
字符(其中chter
僅容納500
1000
字符),您將面臨未定義行為的風險。 第三,您需要通過檢查(1)數字是否轉換來正確驗證 strtol
轉換的結果; (2)通過檢查errno
是否發生溢出/流出 。
將這些放在一起,您可以執行以下操作:
#include <errno.h>
...
if (fr != NULL) //see if file opens or not
{
char chter[500]; //char to get string from text
char *ptr = chter; /* assign chter to the pointer */
char *endptr; /* separate end-pointer for strtol */
fgets(chter, sizeof chter, fr); /* properly limit read size */
printf("%s", chter); //prints current text to cmd from textfile
puts("\n");
errno = 0; /* set errno zero */
while (*ptr && *ptr != '\n') /* loop over all values */
{
long li1 = strtol (ptr, &endptr, 2); /* convert to long */
if (ptr == endptr) { /* validate digits converted */
fputs ("error: no digits converted.\n", stderr);
/* handle error */
break;
}
else if (errno) { /* validate no over/underflow */
perror ("strtol-conversion_failed");
/* handle error */
break;
}
printf (" %ld", li1); /* output value */
ptr = endptr; /* advance pointer */
}
// puts("\n");
putchar ('\n'); /* use putchar for single-char output */
fclose(fr);
}
( 注意:未編譯,如果有問題,請刪除注釋)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.