単語の長さがわからないと、char m[6];
とは書けません。
単語の長さはたぶん10か20くらいだと思います。
キーボードからの入力を得るためにscanf
を使うにはどうしたらいいですか?
#include <stdio.h>
int main(void)
{
char m[6];
printf("please input a string with length=5\n");
scanf("%s",&m);
printf("this is the string: %s\n", m);
return 0;
}
please input a string with lenght=5 hello これは文字列です: hello
エリアをダイナミックに確保しながら入力する。
E.G.
#include <stdio.h>
#include <stdlib.h>
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(char)*size);//size is start size
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(char)*(size+=16));
if(!str)return str;
}
}
str[len++]='\0';
return realloc(str, sizeof(char)*len);
}
int main(void){
char *m;
printf("input string : ");
m = inputString(stdin, 10);
printf("%s\n", m);
free(m);
return 0;
}
より安全な方法を提案させていただきます。
文字列を格納するのに十分な大きさのバッファを宣言します。
char user_input[255];
安全な**方法でユーザー入力を取得します。
fgets(user_input, 255, stdin);
入力を安全に取得する方法で、最初の引数は入力が格納されるバッファへのポインタ、2番目の引数はこの関数が読み込むべき最大の入力、3番目の引数は標準入力へのポインタ、つまりユーザの入力がどこから来るのかを示します。
特に、安全性については、2番目の引数で読み取る量を制限することで、バッファオーバーランを防ぐことができます。また,fgets
は,処理された文字列のヌル終端処理を行います.
この関数についての詳細は ここ を参照してください。
EDIT: 文字列を数値に変換するなどのフォーマットが必要な場合は、入力を得た後に atoi を使うことができます。