|
> scanfで1とスペースを5回、さらに5と入力すると「1 5」と
> 表示されたまま計算されてしまいます。
> 自分としては、「1 5」と入力された後にこれをはじくエラー文を
> 書きたいのですが、うまくif文等が思いつきません。
scanf() では、行単位の入力が出来ません。
fgets() で 1行入力してから、sscanf() で値を取り込むようにしましょう。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void tasu(int x, int y, int *t)
{
*t = x + y;
}
void hiku(int x, int y, int *t)
{
*t = x - y;
}
int get_int(const char *msg)
{
char buf[1024], c; int n;
for (;;) {
puts(msg);
if (fgets(buf, sizeof buf, stdin) == NULL) exit(1);
if (sscanf(buf, "%d %c", &n, &c) == 1) return n;
}
}
void tashizan(int count)
{
int a, b, t;
a = get_int("1番目の値は?");
b = get_int("2番目の値は?");
tasu(a, b, &t);
printf("1番目と2番目の値を足すと %d\n", t);
printf("%d回目の足し算でした\n", count);
}
void hikizan(int count)
{
int a, b, t;
a = get_int("1番目の値は?");
b = get_int("2番目の値は?");
hiku(a, b, &t);
printf("1番目から2番目の値を引くと %d\n", t);
printf("%d回目の引き算でした\n", count);
}
int main(void)
{
char buf[1024], no[1024], c;
int add_count = 0, sub_count = 0;
while (1) {
printf("\n処理の値は(1:足し算, 2:引き算: e:終了)?\n");
if (fgets(buf, sizeof buf, stdin) == NULL) break;
if (sscanf(buf, "%s %c", no, &c) != 1) strcpy(no, "0");
if ( strcmp(no, "1") == 0) tashizan(++add_count);
else if (strcmp(no, "2") == 0) hikizan(++sub_count);
else if (strcmp(no, "e") == 0) break;
else if (strcmp(no, "99")== 0) break;
else printf("再度入力してください\n");
}
printf("処理を終了します\n");
return 0;
}
|