C言語を使用して、タスク情報を記録できるシステムを作成しています。addtaskのコード内から文字列を入力し、その後ファイルに書き換え、viewtaskの画面でtask情報を確認しできるコードを書こうと試みています。しかしコードを実行したところ、printf(Enter your task name:)の文字が表示されたすぐ後に(ENTER id:)が表示され、文字列の入力ができませんでした。
以下にソースコードをupしますので、原因と解決方法をご教授いただけますと幸いです。
c
#include <stdio.h> #include <stdlib.h> void addtask(); void viewtask(); char menu(); int main() { char selection ; do { selection = menu(); switch(selection) { case '1': addtask(); break; case '2': viewtask(); break; case '5': printf("\nThank you for using Task manager!!^^"); exit(0); default: printf("\nYou entered wrong choice..."); printf("\nPress any key to try again"); break; } } while(selection != '9'); return 0; } char menu() { printf("\n\n\nWelcome to Task Management System!"); printf("\nThis is Main Menu"); char option; printf("\n1) Add New Task"); printf("\n2) Check your Task"); printf("\n5) Exit"); printf("\nEnter your choice: "); scanf("%c[^\n]", &option); return option; } void addtask() { char ch[100]; int id, value; printf("\nthis is add your Task"); FILE * f = fopen("data.txt", "r+"); if(f == NULL) f = fopen("data.txt", "w"); else { fseek(f, 0, SEEK_END); printf("\nEnter your task name:"); fgets(ch, sizeof(ch), stdin); printf("\nENTER id:"); scanf("%d", &id); printf("\nEnter value: "); scanf("%d", &value); fprintf(f,"%s %d %d\n", ch, id, value); } fclose(f); } void viewtask(){ char ch[]; int i ,v; printf("\nthis is display record"); FILE * f = fopen("data.txt", "r"); while(fscanf(f,"%s",&ch) != EOF){ fscanf(f,"%d",&i); fscanf(f,"%d",&v); printf("\nTaskname: %s \t id: %d \t Value: %d", ch, i, v); } fclose(f); }
まだ回答がついていません
会員登録して回答してみよう