我試圖從 TXT 檔案中獲取每一行,然后將該行傳遞給變數,我將在 if 陳述句中匹配這些變數。我的txt檔案是:
add $t0, $t1, $t2
addi $t0, $t1, 30352
它正確洗掉逗號并將“add”、“$t0”、“$t1”、“$t2”發送到它們各自的變數,然后使用 if 陳述句將它們轉換為二進制表示。它適用于除 $t2 之外的每個變數,因為有某種隱藏的換行符,我一生都無法弄清楚如何洗掉。我的 if 陳述句看起來像
else if(strcmp("$t2", reg) == 0)
{
return r10;
}
它應該回傳 01010 但從不評估為真。
如何清除 C 中的換行符?
更新:這是我閱讀檔案的方式
FILE *fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
void sendLine()
{
//Open file, check it's not empty
fp = fopen("mymipsfile.txt", "r");
if (fp == NULL)
{
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
remove_all_chars(line, ',');
interpertLine(line);
decodeLine(0);
printf("\n");
}
fclose(fp);
if (line)
{
free(line);
}
exit(EXIT_SUCCESS);
}
這是我如何將其拆分為變數
void interpertLine(char currentLine[])
{
//Extract the first token
char * token = strtok(currentLine, " ");
op = token;
//Loop through the string to extract all other tokens
int i = 0;
while( token != NULL ) {
//printf( " %s\n", token ); //printing each token
token = strtok(NULL, " ");
if(i == 0)
{
rs = token;
}
else if (i == 1)
{
rt = token;
}
else if (i == 2)
{
rd = token;
}
i ;
}
}
uj5u.com熱心網友回復:
只需將比較長度限制為僅可見字符:
else if (strncmp("$t2", reg, sizeof("$t2") - 1) == 0)
{
return r10;
}
注意 1:我使用 'sizeof() - 1' 來防止比較尾隨空終止位元組 (0),存在于每個字串文字“....”的末尾
注2:如果'reg'指向以“$t2”開頭的任何字串,我的解決方案將產生'誤報',例如:“$t20”、“$t2abc”等。所以,更好的方法是替換第一個不可見字符到 0,然后比較全尺寸,如下所示:
char *tmp_reg = reg;
while (tmp_reg )
{
if (tmp_reg < ' ') // is invisible?
{
*tmp_reg = 0; // replace invisible to 0
break; // we don't need to compare more
}
}
// ....
else if (strcmp("$t2", reg)) == 0)
{
return r10;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366247.html
上一篇:c中的while和do-while回圈有什么區別?[復制]
下一篇:為什么我的回圈以次優方式作業?
