基本的に、以下のコードでは、キーボードからファイル名(input.txtとoutput.txt)を読み取ろうとしていますが、「セグメント化エラー」が発生します。また、小文字を大文字に、大文字を小文字に変換します。助言がありますか?私は間違って何をしていますか?キーボードからファイル名を読み取る
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char c;
int charToLowerCase = 0;
int charToUpperCase = 0;
int countCharacters = 0;
FILE *in_file = NULL;
FILE *out_file = NULL;
char str_in[100];
char str_out[100];
char *s_in = NULL;
char *s_out = NULL;
gets(str_in);
gets(str_out);
if (s_in != NULL)
in_file = fopen(str_in, "r");
if (s_out != NULL)
out_file = fopen(str_out, "w");
c = fgetc(in_file);
while (c != EOF)
{
if (c >= 'A' && c <= 'Z')
{
fprintf(out_file, "%c", tolower(c));
charToLowerCase++;
}
else if (c >= 'a' && c <= 'z')
{
fprintf(out_file, "%c", toupper(c));
charToUpperCase++;
}
else
fprintf(out_file, "%c", c);
c = fgetc(in_file);
countCharacters++;
}
fprintf(out_file, "\n");
fprintf(out_file, "Read %d characters in total, %d converted to upper-case, %d to lower-case.\n", countCharacters, charToUpperCase, charToLowerCase);
fclose(in_file);
fclose(out_file);
return 0;
}
'c'は' int'でなければなりません。 'isupper()'と 'islower()'を使うこともできます。 – pzaenger
実際にファイルを開いておき、読み書きを試みます。 's_in == NULL'の代わりに' s_in!= NULL'をテストしますが、テストする必要はありません。その時点ではNULLであることをすでに知っています+彼らは 'fopen(str_in、...)'とは何の関係もありません。 –
誰も 'gets()'を使うべきではありません。 'gets(str_in);'を 'fgets(str_in、sizeof str_in、stdin);に変更してください。 – unwind