C言語プログラムの文字化け
Posted: 2014年6月18日(水) 23:25
こんばんは。
私は今、英文を読み込んで文字ごとに区切り、全て小文字にして出力するプログラムをc言語で作っています。
例)入力:This is a pen. 出力結果:t h i s i s a p e n .
このプログラムは一応完成し、実行しても上手く動いてくれます。
しかし、結果をテキストファイルに出力する際、入力する文章が長い(4行程度)と文字化け?してしまいます
(入力文章が短いと正常に動作します)。
ターミナル上で動かすときは長文でも正常に文字ごとに区切った結果出ますが、
テキストファイルに結果を出力するとダメです…。
文字化けの内容は「・」と無数の乗数の組み合わせです。
OSはwindows8.1、エディタはemacs、ターミナルはminttyで、いずれもwindows対応版です。
ターミナル上では
./alphabet_letter < input.txt > output.txt
と入力しています。今はoutput.txtの中身が文字化けしています。
対策・改善の仕方が分からないので、皆様のご意見をお聞きしたいです。
以下プログラムと入力を貼ります。よろしくお願いします。
<プログラム>
<入力(input.txtの中身)>
As a little girl, I always imagined I would one day run away. From the age of six on, I kept a packed bag with some clothes and cans of food tucked away in the back of a closet. There was a deep restlessness in me, a primal fear that I would fall prey to a life of routine and boredom. And so, many of my early memories involved intricate daydreams where I would walk across borders, forage for berries, and meet all kinds of strange people living unconventional lives on the road.
私は今、英文を読み込んで文字ごとに区切り、全て小文字にして出力するプログラムをc言語で作っています。
例)入力:This is a pen. 出力結果:t h i s i s a p e n .
このプログラムは一応完成し、実行しても上手く動いてくれます。
しかし、結果をテキストファイルに出力する際、入力する文章が長い(4行程度)と文字化け?してしまいます
(入力文章が短いと正常に動作します)。
ターミナル上で動かすときは長文でも正常に文字ごとに区切った結果出ますが、
テキストファイルに結果を出力するとダメです…。
文字化けの内容は「・」と無数の乗数の組み合わせです。
OSはwindows8.1、エディタはemacs、ターミナルはminttyで、いずれもwindows対応版です。
ターミナル上では
./alphabet_letter < input.txt > output.txt
と入力しています。今はoutput.txtの中身が文字化けしています。
対策・改善の仕方が分からないので、皆様のご意見をお聞きしたいです。
以下プログラムと入力を貼ります。よろしくお願いします。
<プログラム>
#include<stdio.h>
#include<string.h>
//小文字にする
void tolower_letter(char *c)
{
char ch = *c - 'A';
(*c) = 'a' + ch;
}
//単語の長さを調べる
int search_length(char str[])
{
int length = 0;
while( str[length] != '\0' ) length++;
return(length);
}
//単語を文字ごとに区切って出力する
void make_alphabet(char str[],int l)
{
int i;
for(i=0; i<l; i++)
if( str[i] >= 'A' && str[i] <= 'Z' ) tolower_letter(&str[i]);
for(i=0; i<l; i++) printf("%c ",str[i]);
}
int main(void)
{
char str[40];
int n,i,length,flag;
do
{
fflush(stdout); //これを書かないとscanfで動作が一旦止まってしまうので書いています
scanf("%s",str);
length = search_length(str);
//「***」が来たらプログラムを終了します(終了条件)。
flag = 0;
if( length == 3 )
for(i=0; i<3; i++)
if( str[i] == '*' ) flag++;
if( flag != 3 ) make_alphabet(str,length);
}
while( flag != 3 );
return(0);
}
As a little girl, I always imagined I would one day run away. From the age of six on, I kept a packed bag with some clothes and cans of food tucked away in the back of a closet. There was a deep restlessness in me, a primal fear that I would fall prey to a life of routine and boredom. And so, many of my early memories involved intricate daydreams where I would walk across borders, forage for berries, and meet all kinds of strange people living unconventional lives on the road.