今度は修正の関数を作っていたのですが、
文字列以外の修正がうまくいきません。
作りたい機能は
・何番目かのデータを選択して一つずつ表示、
変更なしの場合はエンター、変更する場合は入力
・数字のところは半角数字以外が入力されるとエラー、再入力
というものです。どちらか片方なら実現できたのですが・・・
ソースを載せるので訂正すべき点を指摘いただけると助かります。
#include <stdio.h> #include <string.h> #include <stdlib.h> #define BUF 128 typedef struct list { char name[30]; int num; struct list *next; /* 次のデータへのポインタ */ struct list *prev; /* 次のデータへのポインタ */ }List; List *add( char *str,int num, List *head ) { List *p; if ( ( p = ( List * )malloc( sizeof( List ) ) ) == NULL ) { printf( "malloc error\n" ); exit( 1 ); } strcpy( p->name, str ); p->num = num; p->next = NULL; if(head){ List *q = head; while(q->next) q = q->next; q->next = p; }else{ p->next = NULL; head = p; } return head; } List *write(int code, List *head, List *tail) { List *p; char name[30]; int num=1; if (head != NULL){ for ( p = head; p->next != NULL; p = p->next ) num++; num++; } code = 1; while(code==1){ if(code == 4) break; printf( "名前:" ); scanf( "%s", name );getchar(); printf("No.%d\n",num); printf("%s No.%d\n",name, num); head = add( name, num, head ); if( head == NULL ) head = tail; num++; printf("追記:1 終了:4 →"); while(1){ scanf("%d",&code);getchar(); if (code==1 || code==4 ) break; else rewind(stdin); } } return(head); } /*** データ修正 ここの数字入力のところです。***/ List *edit(List *head) { List *p = head; char buf[BUF]; int i, cnt = 0; puts("何番を修正しますか?"); scanf("%d", &i); gets(buf); while (p != NULL) { if (++cnt == i) { printf("変更しない場合は単に[return]を押下\n"); printf("名前: %s -> ", p->name); gets(buf); if (strlen(buf)) strcpy(p->name, buf); printf("番号: %d -> ", p->num); gets(buf); if (strlen(buf)) p->num=atoi(buf);//ここの条件設定です。 return head; } else p = p->next; } puts("番号がありません"); return head; } void dispall( List *p ) { while ( p != NULL) { printf( "%s No.%d\n",p->name,p->num ); p = p->next; } } int main( void ) { List *head= NULL; List *tail= NULL; List *p; int code; while( 1 ) { printf( "入力:1 表示:3 修正:4 終了:5 →"); scanf( "%d", &code );getchar(); if ( code == 5 ) break; else if ( code == 1 ){ head = write(code, head, tail); }else if ( code == 3 ){ dispall(head); }else if ( code == 4 ){ edit(head); }else rewind(stdin); } while ( head != NULL ) { p = head->next; free( head ); head = p; } return 0; }