を入力としてfgets()
読んたび文字列を使用してみてください:ここで
は、あなたのプログラムの修正版です。とにかくここに私が少し修正したコードがあります。自分のニーズに合わせてコードを変更してください。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct movie {
char title[40];
int rate;
int year;
};
int main(){
struct movie m;
char *newline_char=NULL;
puts("What was the title of the movie you saw?");
fgets(m.title,40,stdin);
//The below two lines of code are used to remove the '\n'
//character from the input since fgets() also stores the '\n'
//character. Replace the '\n' char with '\0' character.
if((newline_char=strchr(m.title,'\n')) != NULL){
*newline_char = '\0';
}
puts("What was the relase year?");
fscanf(stdin, "%d", &m.year);
puts("How would you rate the movie? (1-10)");
fscanf(stdin, "%d", &m.rate);
printf("You saw the movie %s which was released %d and you rated it a %d", m.title, m.year, m.rate);
return 0;
}
chuxが推奨するように、またのみfgets()
を使用することができ、コードで以下に示すようにfscanf()
を避けるため、
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct movie {
char title[40];
int rate;
int year;
};
int main(){
struct movie m;
char *newline_char=NULL;
char input[256];
puts("What was the title of the movie you saw?");
fgets(m.title,40,stdin);
if((newline_char=strchr(m.title,'\n')) != NULL){
*newline_char = '\0';
}
puts("What was the relase year?");
fgets(input,256,stdin);
sscanf(input,"%d",&m.year);
puts("How would you rate the movie? (1-10)");
fgets(input,256,stdin);
sscanf(input,"%d",&m.rate);
printf("You saw the movie %s which was released %d and you rated it a %d", m.title, m.year, m.rate);
return 0;
}
'関数fscanf(STDIN、 "%sの"、m.title);' - - > 'fscanf(stdin、"%39 [^ \ n]%* c "、m.title); ' – BLUEPIXY
@BLUEPIXYさて、なぜですか?それは私には奇妙に見えるので、私はそれが実際に何を理解する必要があります。コメントをいただきありがとうございます。 –
'%s'にはスペースが含まれていません。 '%[^ \ n]'は改行文字以外は読み込みます。 – BLUEPIXY