与えられた文字列中から邪魔な行末の改行コードを取り去る関数removeLF()を作ってみよう。
与えられた文字列中から改行コードを取り去る関数removeLF() |
#include <stdio.h> #include <stdlib.h> void removeLF(char str[]) { int i=0; while (str[i]) { if (str[i]=='\n' || str[i]=='\r') str[i]='\0'; i++; } } int main() { FILE *fp; char fname[]="Peter.txt"; char string[512]; /*読み込まれた1行文字列(文字コード)*/ int i; /*ファイルオープンの手続き*/ fp=fopen(fname,"r"); if (fp==NULL) { printf("can't open %s\n",fname); exit(1); } for (i=0; i<3; i++) { /*ファイル先頭の3行の文字列を読み込む*/ fgets(string,510,fp); removeLF(string); printf("%d行目文字列 [%s]\n",i,string); } /*ファイルクローズ*/ fclose(fp); return 0; } |
実行結果 |
0行目文字列 [Peter ran straight away to Mr. McGregor's garden,] 1行目文字列 [and squeezed under the gate!] 2行目文字列 [First he ate some French beans;] |
次のように作った場合は,文字列str[]中に'\n'が含まれていなかった場合に暴走します。
whileループを作るときは,必ず抜け出せるかどうかをチェックしよう。
void removeLF(char str[]) { int i=0; while (str[i]!='\n') { i++; } str[i]='\0'; } |