我正在嘗試從用“#”表示的文本檔案中過濾掉評論。我無法遍歷整個檔案并將輸出列印到終端。該代碼洗掉了第一行文本和第二行注釋,但不會繼續超過第 2 行(列印 4、2),任何幫助將不勝感激。我肯定錯過了一些東西,因為我不得不在一個周末學習兩個學期的 C 語言并且不能完全掌握它的所有用法。
正在讀取的檔案
# this line is a full comment that might be pseudo-code or whatever
4, 2 # 4, 3
1
# 9
7
endNode
endNet
該程式
#include <stdio.h>
#include <string.h>
#define BUFF_SIZE 1024
#define COMMENT_MARKER '#'
int main()
{
FILE *fp;
char buffer[BUFF_SIZE];
if ((fp = fopen("F:\\PythonProjects\\C\\text.txt", "r")) == NULL)
{
perror("Error opening file");
exit(1);
}
while (fgets(buffer, BUFF_SIZE, fp) != NULL)
{
char *comment = strchr(buffer, COMMENT_MARKER);
if (comment != NULL)
{
size_t len = strlen(comment);
memset(comment, '\0', len);
printf("%s", buffer);
}
}
fclose(fp);
}
uj5u.com熱心網友回復:
這是您的代碼,最低限度地適應了實作目標。
#include <stdio.h>
#include <string.h>
#define BUFF_SIZE 1024
#define COMMENT_MARKER '#'
int main()
{
FILE *fp;
if ((fp = fopen("F:\\PythonProjects\\C\\text.txt", "r")) == NULL)
{
perror("Error opening file");
exit(1);
}
char buffer[BUFF_SIZE]; // declare variables proximate to use
while (fgets(buffer, BUFF_SIZE, fp) != NULL)
{
char *comment = strchr(buffer, COMMENT_MARKER);
if (comment != NULL)
{
strcpy( comment, "\n" ); // Just clobber the comment section
}
printf("%s", buffer); // Always print something
}
fclose(fp);
}
uj5u.com熱心網友回復:
如果在其中找到 a,您當前的代碼只會列印出一行#
。它跳過列印行而沒有任何評論。并且因為您將字串從第一個#
到結尾的所有內容都設定為 nul 位元組,所以它不會在每行之后列印換行符,這意味著結果都會一起運行。
您可以通過在注釋洗掉塊之后移動輸出并始終列印換行來解決這些問題。這意味著在沒有注釋的行中,您必須對末尾的換行符做一些事情(如果有的話;它可能因為一行很長或者輸入檔案在最后一行之后缺少一個而丟失)所以你不會得到兩個每個非注釋行之后的換行符。
幸運的是,標準 C 中有一些方法可以找到一組字符的第一次出現,而不僅僅是單個字符。您可以在單行中查找注釋字符或換行符,并將其替換為單個 nul 位元組 - 無需將memset()
其后的所有內容都替換為 0。例子:
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // Needed for exit()
#define BUFF_SIZE 1024
#define COMMENT_MARKER '#'
int main()
{
FILE *fp;
char buffer[BUFF_SIZE];
if ((fp = fopen("text.txt", "r")) == NULL)
{
perror("Error opening file");
exit(1);
}
char tokens[3] = { COMMENT_MARKER, '\n', '\0' };
while (fgets(buffer, BUFF_SIZE, fp) != NULL)
{
// Look for the first # or newline in the string
char *comment_or_nl = strpbrk(buffer, tokens);
if (comment_or_nl)
{
// and if found, replace it with a nul byte
*comment_or_nl = '\0';
}
// Then print out the possibly-truncated string (puts() adds a newline)
puts(buffer);
}
fclose(fp);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/505655.html