概述
void menu() {
int op;
printf("n Choose a option from below : nn");
printf(" 1: Add Contactn"
" 2: View A Contactn"
" 3: View All Contactsn"
" 4: View All Contacts With a Common First Charactern"
" 5: Delete All Contactn"
" 6: Delete A Contactn"
" 7: Replace A Contact Namen"
" 8: Replace A Contact Numbern"
" 9: Refreshn"
" 10: Exitnn");
printf(" Which one ? ");
fgets(op, 5, stdin);
switch ((int)op) {
case 1: addrecords(); break;
case 2: viewone(); break;
case 3: viewall(); break;
case 4: viewonechar(); break;
case 5: deleteall(); break;
case 6: deleteone(); break;
case 7: replaceone(); break;
case 8: replaceonenumber(); break;
case 9: refresh(); break;
case 10: exit(0); break;
default:
printf ("n Wrong Option.nn");
menu();
break;
}
}
void addrecords() {
char name[50];
char number[20];
printf("nn Enter Contact Number (+880) : "); //Skips this
fgets(number, 20, stdin);
check(number);
printf(" Enter Contact Name : "); //Comes in here
fgets(name, 50, stdin);
fp = fopen("Phonebook.txt","a");
fprintf(fp, "%s %sn", name, number);
fclose(fp);
printf("n Contact Successfully Saved!n Returning To Main Menu...nn");
menu();
}
void check(char n[20]) {
char name[25];
char ncheck[20];
fp = fopen("Phonebook.txt", "r");
fscanf(fp, "%s %s", name, ncheck);
while (!feof(fp)) {
if ((strcmp(ncheck, n)) == 0) {
printf ("n Contact Already Exists.nn");
fclose(fp);
menu();
} else {
fscanf (fp, "%s %s", name, ncheck);
}
}
}
好吧我编辑了我的程序。我输入1后,程序说错了选项。但我正在写入一个。虽然我做得对,但为什么程序显示错误的选项?这是否与fgets?现在有什么问题?scanf和fgets在同一个程序中
+0
没有办法让scanf不留任何换行符吗? –
+0
我的建议:不要使用'scanf',而是用你需要写的函数替换它,比如'int GetInteger()'。使用''fgets''(http)替换'scanf('%d',&op);'''GetInteger()'''GetInteger()'函数非常容易编写~3-4行代码。 ://www.cplusplus.com/reference/cstdio/fgets/)和['atoi'](http://www.cplusplus.com/reference/cstdlib/atoi/) –
+0
请看[Why is“while( !(feof(file))“总是错?](http://stackoverflow.com/q/5431941/2173917) –
最后
以上就是苹果溪流为你收集整理的c语言fgets和scanf,scanf和fgets在同一个程序中的全部内容,希望文章能够帮你解决c语言fgets和scanf,scanf和fgets在同一个程序中所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复