tomo.xxxです。
コンソールに担当者名を入力してコンソールに担当者名に"end"と打ち込まれるまでテキストファイルに担当者名を書いていくというプログラムをC言語で作りました。
下のプログラムの26行目のようにif(strcmp(tantou, "end\n") == 0)と書くと、このプログラムは自分の思ったように動作する(endをコンソールに打ち込み、リターンするとプログラムが終了する)のですが、if(strcmp(tantou, "end") == 0)と書くとendとコンソールに打ち込み、リターンしてもループを回り続けるプログラムになりました。
自分はfgetsの仕様の問題だと思っているのですが、どなたかこの理由を詳しく教えていただけませんか?
実行コマンド
./a.exe filename(テキストファイル名) mode(モード)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input_tantou();
void write_file();
int main(int argc, char *argv[])
{
FILE *fp;
int i,j;
char *tantou;
fp = fopen(argv[1], argv[2]);
if(fp == NULL){
printf("Error!!\n");
exit(1);
}
fprintf(fp, "tantou\n");
fprintf(fp, "------------\n");
while(1){
// 担当者名入力
input_tantou(tantou);
if(strcmp(tantou, "end\n") == 0){
break;
}
else{
// 担当者をテキストファイルに記入
write_file(tantou, fp);
printf("%s", tantou);
}
fflush(stdin);
}
fclose(fp);
return 0;
}
// 担当者の名前を入力
void input_tantou(char *tantou)
{
printf("tantou:");
fgets(tantou, 20, stdin);
}
// ファイルに担当者の名前を書き込む
void write_file(char *tantou, FILE *fp)
{
fprintf(fp, "%s\n", tantou);
}