我正在使用getchar和putchar(來自Ritchie C書)進行文本格式化。我能夠消除'//'的評論,但是在刪除空白行中的一些換行符時遇到了問題。我想從源文件中消除行註釋「//」和「blanK」換行符 - 沒有任何文本的行。讀取文件時,來自getchar/putchar的意外返回值^ M
我在輸出文件中出現奇怪的^ M字符。
似乎if語句檢查前面的char(pre)和當前char c是否都是'\ n'正在創建錯誤。
如果你刪除此不再給人怪異的輸出:
else if(c == '\n' && pre == '\n')
{
pre = c;
}
全部下面的代碼:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
main()
{
int c;
int pre;
int comment = 0;
while ((c = getchar()) != EOF)
{
// printf("%c", c);
// printf("pre is %c comment is %d c is %c\n", pre, comment, c);
// check to see if we're at a newline and set comment toggle to 0
if(c == '\n' && comment ==1)
{
comment = 0;
pre = c;
}
else if(c == '\n' && pre == '\n')
{
pre = c;
}
else if(comment == 1)
{
pre = c;
}
else if(pre == '/' && c == '/')
{
comment = 1;
pre = c;
}
else if(c == '/')
{
pre = c;
}
else if(pre =='/')
{
putchar(pre);
putchar(c);
pre = c;
}
else
putchar(c);
}
return 0;
}
輸入文件是Add.asm。
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/06/add/Add.asm
// Computes R0 = 2 + 3 (R0 refers to RAM[0])
@2
D=A
@3
D=D+A
@0
M=D
輸出文件是bdd.hack,它看起來在github罰款,但是當我用vim打開它看起來是這樣的:
^M^[email protected]^MD=A^[email protected]^MD=D+A^[email protected]^MM=D
C程序是assembler.c。 我喜歡這個 CC assembler.c在命令行上調用此 ./a.out bdd.hack
github repo with input file Add.asm, output file bdd.hack, and program to format text assembler.c
注:這是一個自我學習課程NAND俄羅斯方塊 - 我用C語言寫這篇文章b/c我在學習C語言,並認爲這將是一個有趣的C語言項目(一個基本的彙編程序)。您可以忽略assembler.c底部的僞代碼。
請不要張貼鏈接到代碼。改爲發佈代碼。見[問]。 –
^m是一個回車...在Windows文本文件行結束與回車,其次是一個換行...你應該去除兩個 – TonyB
@TonyB我目前在Windows 10上的虛擬框上運行debian。會這樣如果我在虛擬盒子上運行Debian會影響我嗎? – theporpoise