读取文件时来自getchar / putchar的意外返回值^ M.

时间:2016-10-15 21:30:20

标签: c

我正在使用getchar和putchar进行文本格式化(来自Ritchie C一书)。我能够消除' //'评论,但我在删除空行上的一些换行符时遇到问题。我想删除行注释' //'和" blanK"换行符 - 源文件中没有任何文本的行。

我在输出文件中得到了奇怪的^ M个字符。

if else语句似乎检查前一个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^M@2^MD=A^M@3^MD=D+A^M@0^MM=D

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 / C中写这个我学习C并认为这将是一个有趣的项目在C(基本汇编语言)。您可以忽略assembler.c底部的伪代码。

1 个答案:

答案 0 :(得分:0)

这是一个Windows文本文件,因此上面有TonyB建议的^ M个字符。我使用dos2unix在我的debian系统上正确格式化文件,问题解决了。谢谢大家的帮助!

相关问题