スタックのプログラムを見てわからないことがありました。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int top, S[1000];
void push(int x) {
S[++top] = x;
}
int pop() {
top--;
return S[top + 1];
}
int main() {
int a, b;
top = 0;
char s[100];
while (scanf("%s", s) != EOF) { if (s[0] == '+' ) { a = pop(); b = pop(); push(a + b); } else if (s[0] == '-' ) { a = pop(); b = pop(); push(a - b); } else if (s[0] == '*' ){ a = pop(); b = pop(); push(a * b); } else { push(atoi(s)); } } printf("%d\n", pop()); return 0;
}
コードは上記の通りなのですが、わからないのはscanf周りやatoi()のことです。
例えば入力が、文字列型の[1 2 + CTRL+Z]だとしたら、
まず1をatoi()で数値に変えます。
このときに引数がsとなっていますが、s[0]ではないのでしょうか?
そして、次の2を示すのはs[1]なので、while(){}内の条件でs[0]が指定されているのは、どういうことなのでしょうか?
以上2点、よろしくお願いします。
回答3件
あなたの回答
tips
プレビュー