Пример #1
0
// ([0-9]|(~!@#$%^&*-+=\/)|[a-z])*[a-z]+([0-9]|(~!@#$%^&*-+=\/)|[a-z])
int read_symbol(FILE *in, struct value *val)
{
  char c;
  const char valid_chars[] = "~!@#$%^&*-+=/\\";
  unsigned int i, non_numerical_seen = 0;

  for (i = 0; i < MAX_SYMBOL_SIZE; i++) {
    c = fgetc(in);
    if (isdelim(c)) {
      break;
    } else if (!(isalnum(c) || strchr(valid_chars, c))) {
      val->symbol[i+1] = 0;
      ungets(val->symbol, in);
      return READ_INVALID_CHAR;
    } else if (!isdigit(c) && !non_numerical_seen) {
      non_numerical_seen = 1;
    }
    val->symbol[i] = c;
  }
  val->symbol[i] = 0;
   
  if (!val->symbol[0] || !non_numerical_seen) {
    ungets(val->symbol, in);
    return READ_FAIL;
  } else {
    val->type = SYMBOL;
    return READ_SUCCESS;
  }
}
Пример #2
0
/* reverse Polish calculator */
main()
{
    char s[] = "string to push onto input\n";
    
    ungets(s);
    printf("%s", s);
}
Пример #3
0
int main(int argc, char *argv[])
{
    double op2;
    char s[MAXOP];
    while(--argc > 0){
        ungets(" ");
        ungets(*++argv);
        switch(getop(s)){
            case NUMBER:
                push(atof(s));
                break;
            case '+':
                push(pop() + pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                op2 = pop();
                push(pop() - op2);
                break;
            case '/':
                op2 = pop();
                if(op2 != 0.0)
                    push(pop() / op2);
                else
                    printf("error: zero divisor\n");
                break;
            case '%':
                op2 = pop();
                if(op2 != 0.0)
                    push(fmod(pop(), op2));
                else
                    printf("error: zero divisor\n");
                break;
            case '\n':
                printf("\t%.8g\n", pop());
                break;
            default:
                printf("error: unknown command %s\n", s);
                argc = 1;
                break;
            }
    }
    printf("\t%.8g\n", pop());
    return 0;
}
Пример #4
0
Файл: ex4_7.c Проект: yufw/kr
int main()
{
    int c;
    
    ungets("hello, world\n");
    while ((c = getch()) != EOF)
        putchar(c);
    return 0;
}
Пример #5
0
int main() {
	/* Example usage */
	char c;
	ungets("hello");
	while ((c = getch()) != 'o')
		putchar(c);
	putchar(c);
	return 0;
}
Пример #6
0
/*
 * To better cope with complexity and to reduce the load on the preprocessor
 * and the compiler, C programs exploit modularity, a software design technique
 * that revolves on organizing code on independent, interchangeable modules
 * each containing just one specific functionality out of all those provided by
 * a larger program.
 * One of the key concepts of modularity is that each module should 'know', or
 * contain, only the bare minimum needed to perform its functionality.
 * As such the ungets(s) function of this exercise, should just use ungetch,
 * without 'knowing' details about its implementation, but only its interface.
 */
int main(void)
{
	char s[MAXLINE];

	/* read an input line and push it back onto the s string */
	ungets(s);
	printf("%s", s);
	return 0;
}
Пример #7
0
int main()
{
	char *s = "hello, world.  this is a test.";
	int c;
	ungets(s);
	while ((c = getch()) != EOF)		// 通过 getch() 从 buf 中取字符到,并且逐个输出字符
	   putchar(c); 
	return 0;
}
Пример #8
0
int main(int argc, char *argv[]) {

    char   operator[MAXOP] = ""; // Operator
    double operand;              // Temporary operand

    // Start the REPL (read, evaluate, and print loop)

    while (--argc > 0) {

        ungets(" ");      // Push end of argument
        ungets(*++argv);  // Push an argument

        switch(getop(operator)) {
            case NUMBER:
                dapush(atof(operator));
                break;
            case '+':
                dapush(dapop() + dapop());
                break;
            case '-':
                operand = dapop();
                dapush(dapop() - operand);
                break;
            case '*':
                dapush(dapop() * dapop());
                break;
            case '/':
                operand = dapop();
                dapush(dapop() / operand);
                break;
            default:
                printf("Error: Unknown command '%s'\n", operator);
                argc = 1;
                break;
        } // switch

    } // while

    printf("%.8g\n", dapop());

    return 0;
}
int main(void)
{
	int c;

	ungets("String to test : ) \n");
	while (bufp > 0) {
		c = getch();
		putchar(c);
	}	
	return 0;
}	
void getch

int main()
{
    int c;
    char *string="pushing characters back to its input";
    ungets(string);
    while((c=getch()) != EOF)
        putchar(c);
    return 0;
}
Пример #11
0
int main()
{
	char s[MAXOP];
	getop(s);
	printf("s=%s\n", s);
	ungets(s);
	getop(s);
	printf("s=%s\n", s);
	getop(s);
	printf("s=%s\n", s);
	return 0;
}
Пример #12
0
main(void)
{
	char c;
	char ms[] = "Hello this is the test input.\n"; 
	ungets(ms);
	while((c = getch()) != '\n'){
		putchar(c);
	}
	putchar('\n');
	
	return 0;
}
Пример #13
0
int main(int argc, char **argv)
{
    char   s[MAXOP];
    double op2;

    while (--argc > 0) {
        ungets(" ");
        ungets(*++argv);

        switch (getop(s)) {
            case NUMBER:
                push(atof(s));
                break;
            case '+':
            case '*':
                push(pop() + pop());
                break;
            case '-':
                op2 = pop();
                push(pop() - op2);
                break;
            case '/':
                op2 = pop();
                if (op2 == 0) {
                    fprintf(stderr, "error: zero divisor\n");
                    return -1;
                }
                push(pop() / op2);
                break;
            default:
                fprintf(stderr, "error: unknown command %s\n", s);
                argc = 1;   /* next step is to jump out of while loop */
                break;
        }
    }

    printf("\t%.8g\n", pop());  /* print the result */

    return 0;
}
Пример #14
0
/* standard input/output functions */
void ungets (char c[]);
int getch(void);
int ungetch(int); /* tare smekeră funcţia asta : 
                      face push la o valoare intr-un buffer 
                      pe care il imparte cu getch 
                   */
int main(void)
{
   int i = 0;
   char s[MAXOP + 1] = "ceva plus \0 ceva";

   ungets(s);

   printf("\n Your string containing EOF is");
   while(buf[i] > 0)
      printf("%c", buf[i++]);

   return 0;
}
Пример #15
0
int main(int argc, char const *argv[])
{
  char s[] = "Write a routine ungets(s) that will push back an entire string onto the input.";
  char c;

  ungets(s);

  while((c = getc()) != EOF)
  {
    putchar(c);
  }

  return 0;
}
Пример #16
0
int read_string(FILE *in, struct value *val)
{
  char c;
  unsigned int i;

  if ((c = fgetc(in)) != '\"') {
    ungetc(c, in);
    return READ_FAIL;
  }

  for (i = 0; (c = fgetc(in)) != '\"'; i++) {
    if (EOF == c) {
      val->string.arr[i] = 0;
      ungets(val->string.arr, in);
      return READ_MISMATCH_DELIM;
    } else if ('\\' == c) {
      c = fgetc(in);
      if ('n' == tolower(c)) {
	val->string.arr[i] = '\n';
      } else if ('t' == tolower(c)) {
	val->string.arr[i] = '\t';
      } else if ('\"' == c) {
	val->string.arr[i] = '\"';
      } else {
	val->string.arr[i] = 0;
	ungets(val->string.arr, in);
	return READ_INVALID_CHAR;
      }
    } else {
      val->string.arr[i] = c;
    }
  }

  val->type = STRING;
  val->string.len = i;
  return READ_SUCCESS;
}
Пример #17
0
main()
{
    char s[100];
    int c,i;
    i=0;
    while((c=getchar())!='q')
    {
        s[i++]=c;
    }
    ungetch(c);
    printf("%c\n",getch());
    ungets("98");
    printf("%c\n",getch());
    printf("%c\n",getch());
    return 0;
}
Пример #18
0
main()
{
	char w[MAXWORD];
	struct nlist *p;

	while (getword(w, MAXWORD) != EOF)
		if (strcmp(w, "//") == 0)
			getdef();
		else if (!isalpha(w[0]))
			printf("%s", w);
		else if ((p = lookup(w)) == NULL)
			printf("%s", w);
		else
			ungets(p->defn);
	return 0;
}
Пример #19
0
// getlinef: get line with delimeter, and then the rest until '\n'
int getlinef(char ln[], char d[], int lim) {
	int i, k, c, j;
	char rest[lim];
	for (i=k=0; i<lim && d[k] != '\0'; ++i) {
		ln[i] = (c=getch());
		if (c == d[k]) ++k;
		else k = 0;
	}
	i -= k;
	ln[i] = '\0';
	for (j=0; j<lim && (c=getch()) != EOF && c != '\n'; ++j,++i)
		rest[j] = c;
	rest[j] = '\0';
	ungets(rest);
	return i;
}
Пример #20
0
int main(void) {

    char buffer[BUFFER_SIZE] = { 0 };

    char c = 0;
    char d = 0;

    while (1)
    {
        fgets(buffer, BUFFER_SIZE, stdin);
        printf("%s\n", buffer);
        ungets(buffer, stdin);
    }

    getchar();
    return 0;
}
Пример #21
0
int read_character(FILE *in, struct value *val)
{
  char c, special_char;
  char buf[BUF_LEN] = {0};
  char special_str[BUF_LEN] = {0};
  unsigned int special_len, i;

  if ((c = fgetc(in)) != '#') {
    ungetc(c, in);
    return READ_FAIL;
  }

  if ((c = fgetc(in)) != '\\') {
    ungetc(c, in);
    return READ_FAIL;
  }

  c = fgetc(in);

  if (tolower(c) == 'n') {
    special_char = '\n';
    strcpy(special_str, "newline");
  } else if (tolower(c) == 't') {
    special_char = '\t';
    strcpy(special_str, "tab");
  } else if (tolower(c) == 's') {
    special_char = ' ';
    strcpy(special_str, "space");
  }

  if (special_str[0]) {
    special_len = strlen(special_str);
    for (i = 1; i < special_len; i++) {
      buf[i-1] = c = fgetc(in);
      if (tolower(c) != special_str[i]) {
	ungets(buf, in);
	return READ_INVALID_CHAR;
      }
    }
    val->character = special_char;
  } else {
    val->character = c;
  }

  return READ_SUCCESS;
}
Пример #22
0
void ParseParamList(char *desc) {
  int type;
  char token[kMaxToken];

  do {
    ParseParamDecl(desc);
    type = GetToken(token);

    if (type == ',') {
      strcat(desc, ",");
    } else {
      break;
    }
  } while (1);

  // out of param list
  ungets(token);
}
Пример #23
0
int main(void) {
	printf("Write a routine ungets(s) that will push back an entire string onto the input.\n"
		"Should ungets know about buf and bufp, or should it just use ungetch?\n");

	printf("\nungets(s) should know about buf and bufp, since it can use that to determine if\n"
		"the line to be placed in buf has enough space ready for it.\n");

	printf("Please enter line of text: ");

	ungets("This pre-ungotten string should appear first. ");

	char c;
	int i = 0;
	while ((c = getch()) != '\n' && c != EOF) {
		outString[i++] = c;
	}
	outString[i++] = '\0';
	printf("\nPrinting received input from getch(): %s\n", outString);

	return EXIT_SUCCESS;
}
Пример #24
0
/* (+|-|\0)[0-9]*.[0-9]+ */
int read_flonum(FILE *in, struct value *val)
{
  char c;
  char buf[BUF_LEN] = {0};
  unsigned int i = 0, neg = 0, decimal_seen = 0;
    
  c = fgetc(in);
 
  if ('-' == c) {
    neg = 1;
  } else if (isdigit(c)) {
    buf[i++] = c;
  } else if ('.' == c) {
    decimal_seen = 1;
    buf[i++] = '0';
    buf[i++] = '.';
  } else if ((EOF == c) || (c != '+')) {
    ungetc(c, in);
    return READ_FAIL;
  }

  while (i < BUF_LEN) {
    c = fgetc(in);
    if ('.' == c)
      decimal_seen = 1;
    else if (!isdigit(c)) 
      break;
    buf[i] = c;
    i++;
  }

  if (decimal_seen) {
    val->flonum = atof(buf) * (neg ? -1 : 1);
    val->type = FLONUM;
    return READ_SUCCESS;  
  } else {
    ungets(buf, in);
    return READ_FAIL;
  }
}
Пример #25
0
main()
{
	int ch,i;
	char s[100];
	
	for(i=0;i<100;i++)
		s[i]='\0';
	i=0;
	printf("\nEnter the string : ");
	while((ch=getch())!=EOF && ch!='\n')
		s[i++]=ch;
	s[i]=0;

	printf("\nString is %s",s);
	ungets(s);
	printf("\nAfter ungets %s",s);
	i=0;
	while((ch=getch())!=EOF && ch!='\n' && ch!='\0')
		s[i++]=ch;
	printf("\nAfter using ungets and the getch");
	printf(" :%s\n",s);
}
Пример #26
0
/* (+|-|/0)[0-9]+ where /0 is a null token */
int read_fixnum(FILE *in, struct value *val)
{
  char c;
  char buf[BUF_LEN] = {0};
  unsigned int i = 0, neg = 0;

  c = fgetc(in);

  if ('-' == c) {
    neg = 1;
  } else if (isdigit(c)) {
    buf[i++] = c;
  } else if ((EOF == c) || (c != '+')) {
    ungetc(c, in);
    return READ_FAIL;
  }
    
  while ((EOF != (c = fgetc(in))) && (i < BUF_LEN)) {
    if (isdigit(c)) { 
      buf[i] = c;
    } else if (isdelim(c)) {
      ungetc(c, in);
      break;
    } else {
      ungets(buf, in);
      return READ_INVALID_CHAR;
    }
    i++;
  }

  if (buf[0] != 0) {
    val->type = FIXNUM;
    val->fixnum = atoi(buf) * (neg ? -1 : 1);
    return READ_SUCCESS;
  } else {
    return READ_FAIL;
  }
}
Пример #27
0
/* калькулятор с обратной польской записью */
int main(void)
{
    int type;
    double op1, op2;
    char s[MAXOP];
    for (int i = 0; i < CALPHABET; i++)
        var[i].isInit = false;
    while ((type = getop (s)) != EOF) {
        switch (type) {
            case NUMBER:
                push (atof (s));
                break;
            case OPERAT:
                // определить операцию
                if (strequ(s, "sin", 3)) {
                    push( sin( pop() ) );
                    break;
                } else if (strequ(s, "exp", 3)) {
                    push( exp( pop() ) );
                    break;
                } else if (strequ(s, "pow", 3)) {
                    push( pow(pop(), pop()));
                    break;
                }else if (strequ(s, "ungets", 6)) {
                    if (!fungets) {
                        ungets(s);
                    } else {
                        printf("Данные были возвращены в стандартный поток в\\в\n");
                    }
                    fungets = !fungets;
                    break;
                }
                printf("ошибка: неизвестная операция %s\n", s);
                break;
            case VARIABLE:
                printf("добавлена переменная: ");
                putchar(lastVar.name);
                printf("=%.8g\n", lastVar.value);
                break;
            case '!': // Печатаем верхний элемент стека
                printf("\ttop> %.8g\n", top());
                break;
            case '@': // Дублируем верхний элемент стека
                clonetop();
                break;
            case '#': // Меняем местами два верхних элемента стека
                xchg();
                break;
            case '$': // Очищаем стек
                clear();
                break;
            case '%':
                op2 = pop();
                if (op2 != 0.0) {
                    op1 = pop();
                    push( op1 - op2 * (int)(op1 / op2) );
                }
                else
                    printf("ошибка: деление на нуль\n");
                break;
            case '+':
                push (pop() + pop());
                break;
            case '*':
                push (pop() * pop());
                break;
            case '-':
                op2 = pop();
                push (pop() - op2);
                break;
            case '/' :
                op2 = pop();
                if (op2 != 0.0)
                    push (pop() / op2);
                else
                    printf("ошибка: деление на нуль\n");
                break;
            case '\n' :
                printf("\t%.8g\n", pop());
                break;
            default:
                printf("ошибка: неизвестная операция %s\n", s);
                break;
        }
    }
    return 0;
}
Пример #28
0
int main(int argc, char *argv[])
{
	char word[MAXWORD];

	if (argc != 2) {
		printf("please enter the file name!\n");
		return -1;
	}
	char *filename;
	filename = argv[1];
	FILE * fp;
	if ((fp = fopen(filename, "r")) == NULL) {
		printf("file is not exist!\n");
		return -1;
	}
	char buffer[4096]; //how dirty it is..
	int i = 0;
	while (!feof(fp)) {
		buffer[i++] = fgetc(fp);
	}
	/** 
	 * that is the problem in func void ungets(char s[]) : int len = strlen(s);
	 * pay attention !!!!! the EOF will store in the buffer[i - 1], replace it with '\0'
	 */
	buffer[i - 1] = '\0';
	fclose(fp);
	ungetch(EOF); //it is necessary!
	ungets(buffer);

	int linenow = 1;
	struct nlist *node;
	struct nlist *node_parent;
	while (getword(word, MAXWORD) != EOF) {
		if ((word[0] == '\n')) {
			linenow++;
		}

		if (word[1] == '\0' && !isalpha(word[0])) { //caocaocao == is not =
			continue;
		}

		int hash_key = simple_hash(word, HASHSIZE);
		node = hashtab[hash_key];
		int is_node_exist = 0;
		while (node != NULL) {
			if (strcmp(node->name, word) == 0) {
				is_node_exist = 1;
				node->lines[node->linecount++] = linenow;
				break;
			}
			node_parent = node;
			node = node->next;
		}
		if (!is_node_exist) {
			node = talloc();
			node->next = NULL;
			node->name = strdupp(word);
			node->linecount = 0;
			node->lines[node->linecount++] = linenow;
			//the implement is dirty, how can I keep the consistency?
			if (hashtab[hash_key] == NULL) {
				hashtab[hash_key] = node;
			} else {
				node_parent->next = node;
			}
		}
	}
	for (i = 0; i < HASHSIZE; i++) {
		node = hashtab[i];
		while (node != NULL) {
			printf("%s:", node->name);
			int count = node->linecount;
			while (count--) {
				printf(" %d", node->lines[count]);
			}
			printf("\n");
			node = node->next;
		}
	}
	return 0;
}
Пример #29
0
/* Simple version of #define and #undef processor. */
int main() {
  char word[kMaxWord];
  char *name;
  char defn[kMaxWord];
  LinkNode *p;
  int len = 0, i = 0;
  enum ParserState state = kStart;

  HashTable hash_table[kHashSize];
  HashInit(hash_table, kHashSize);

  memset(word, 0, kMaxWord);
  memset(defn, 0, kMaxWord);

  while (GetWord(word, kMaxWord) != EOF) {
    switch (state) {
      case kStart:
        if (strcmp(word, "#define") == 0) {
          state = kDefine;
        } else if (strcmp(word, "#undef") == 0) {
          state = kUnDef;
        } else if (!isalpha(word[0])) {
          printf("%s", word);
        } else if ((p = HashSearch(hash_table, word)) == NULL) {
          printf("%s", word);
        } else {
          ungets(p->defn);
        }
        break;
      case kDefine:
        if (isalpha(word[0])) {
          name = strdup(word);
          state = kName;
        } else {
          printf("Error: non-alpha name");
          exit(1);
        }
        break;
      case kName:
        if (word[0] == '\n') {
          printf("Error: incomplate define");
          exit(1);
        } else {
          strcpy(defn, word);
          len += strlen(word);
          state = kDefn;
        }
        break;
      case kDefn:
        if (word[0] != '\n' && len < kMaxWord) {
          strcat(defn, word);
          len += strlen(word);
        } else {
          HashInsert(hash_table, name, defn);
          state = kStart;
        }
        break;
      case kUnDef:
        if (isalpha(word[0])) {
          HashDelete(hash_table, name);
          state = kStart;
        } else {
          printf("Error: non-alpha name");
          exit(1);
        }
        break;
    }
  }
  return 0;
}
Пример #30
0
/* reverse Polish calculator
 *
 * all basic operators provided (+, *, -, /, %, sin, exp, pow) as well as some
 * speciality commands:
 *
 *  ` - clear stack
 *  # - duplicate top value of stack
 *  ? - print top value of stack
 *  ~ - swap top two values on stack
 *
 *  variables (a-z) are also supported with the = operator
 *
 *  the '!' character is a special variable which stores the most recently
 *  printed value
 *
 */
int main() {
  int type;
  double op1, op2, last_printed;
  char s[MAXOP];

  while ((type = getop(s)) != EOF) {
    switch (type) {
    case NUMBER:
      push(atof(s));
      break;
    case '+':
      push(pop() + pop());
      break;
    case '*':
      push(pop() * pop());
      break;
    case '-':
      op2 = pop();
      push(pop() - op2);
      break;
    case '/':
      op2 = pop();
      if (op2 != 0.0) {
        push(pop() / op2);
      } else {
        printf("error: zero divisor\n");
      }
      break;
    case '%':
      op2 = pop();
      op1 = pop();
      if (op2 != 0.0) {
        push(op1 - (int)(op1/op2) * op2);
      } else {
        printf("error: zero divisor\n");
      }
      break;
    case SIN:
      push(sin(pop()));
      break;
    case EXP:
      push(exp(pop()));
      break;
    case POW:
      op2 = pop();
      push(pow(pop(), op2));
      break;
    case '`':
      clear();
      break;
    case '#':
      duplicate();
      break;
    case '?':
      print();
      break;
    case '~':
      swap();
      break;
    case VAR:
      /* TODO: Add variable saving */
      op2 = vars['z'-current_var];
      push(op2);
      break;
    case '=':
      op2 = pop();
      vars['z'-current_var] = op2;
      break;
    case '!':
      push(last_printed);
      break;
    case '\n':
      last_printed  = pop();
      printf("\t%.8g\n", last_printed);
      break;
    default:
      printf("error: unknown command %s\n", s);
      break;
    }
  }
  ungets("1 2 +\n");
  printf("Current buffer: %s", buf);
  return 0;
}