C99转ANSI注释程序文件输入异常,终端输入正常问题排查
问题:C99风格注释转ANSI C注释程序的文件输入异常
我写了一个程序,用来将输入文本中的C99风格注释转换为等价的ANSI C注释。该程序在在线终端、通过终端手动输入文本时运行正常,但通过文件输入文本时出现异常。调试发现,初始化值为0的incomment变量在文件输入的第一次循环时变为1,导致程序逻辑出错。我尝试过将incomment初始化为-1并在首次循环重置,也更换过PowerShell、Bash等终端,但问题仍存在。
预期调用#1
// My useful program #include <stdio.h> int main() { /* Our main function */ printf("Hello world!\n"); // print hello // done, phew! return 0; }
预期输出
/* My useful program */ #include <stdio.h> int main() { /* Our main function */ printf("Hello world!\n"); /* print hello */ /* done, phew! */ return 0; }
预期调用#2
//// ***** this code is bad, comment it out ***** // printf("Hello world\n"); /* prints hello world */ // return 0; // /* done, phew! */
预期输出2
/*// ***** this code is bad, comment it out ***** */ /* printf("Hello world\n"); prints hello world */ /* return 0; */ /* done, phew! */
程序代码
#include <stdio.h> #define STAR 42 #define FWDSLASH 47 int main(int argc, char *argv[]) { int ch, incomment = 0, slashlast = 0, starlast = 0; while ((ch = getchar()) != EOF) { // check if line is in comment if (incomment) { // Ignore any other /* combinations if (ch == '/') { if (starlast) { starlast = 0; continue; } if (slashlast) { printf("/"); } slashlast = 1; } // if newline found, set end */ else { if (ch == '*') { if (slashlast) { slashlast = 0; continue; } if (starlast) { printf("*"); } starlast = 1; } else { if (ch == '\n') { if (starlast) { printf("*"); starlast = 0; } else if (slashlast) { printf("/"); slashlast = 0; } incomment = 0; printf(" */"); putchar(ch); } else { if (starlast) { printf("*"); putchar(ch); } else if (slashlast) { printf("/"); putchar(ch); } else { putchar(ch); } starlast = 0; slashlast = 0; } } } } else { // Not in comment //Check for // combination and replace with /* combination if (ch == FWDSLASH) { //Two slashes foud if (slashlast) { incomment = 1; printf("/*"); // Done checking for slashes slashlast = 0; } else { slashlast = 1; } } else { if (slashlast) { // Print the previous slash then print self. printf("/"); putchar(ch); slashlast = 0; } else { putchar(ch); slashlast = 0; } } } } return 0; }
内容的提问来源于stack exchange,提问作者NovaT
相关产品推荐
相关产品推荐

