@marcopaganini/

Simple Data Entry

C

Exemplo de entrada de dados simples via teclado (strings & float). Use como base para as suas próprias funções.

fork
loading
Files
  • main.c

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.5430380245532134","path":"main.c","file":{"path":"main.c","content":{"asEncoding":{"base64":"I2luY2x1ZGUgPHN0ZGlvLmg+CgovKiBQcm90b3R5cGVzICovCmludCBnZXRfc3RyaW5nKGNoYXIgKnByb21wdCwgY2hhciAqc3RyLCBzaXplX3Qgc2l6ZSk7CmludCBnZXRfZmxvYXQoY2hhciAqcHJvbXB0LCBmbG9hdCAqdmFsKTsKCi8qIE1haW9yIHRhbWFuaG8gZGUgdW1hIGxpbmhhIGRlIGVudHJhZGEgKGZsb2F0KSAqLwojZGVmaW5lIE1BWEZMT0FUTEVOIDMyCgovKiBNYWlvciB0YW1hbmhvIGRvIHN0cmluZyAqLwojZGVmaW5lIE1BWFNUUklOR0xFTiAxMAoKaW50IG1haW4oKSB7CiAgaW50IHJldDsKICBmbG9hdCBmOwogIGNoYXIgc3RyW01BWFNUUklOR0xFTiArIDFdOwogIAogIGdldF9zdHJpbmcoIkVudGVyIHN0cmluZzogIiwgc3RyLCBzaXplb2Yoc3RyKSk7CiAgCiAgaWYgKGdldF9mbG9hdCgiRW50cmUgdW0gdmFsb3IgZW0gcG9udG8tZmx1dHVhbnRlIiwgJmYpICE9IDEpIHsKICAgIGZwcmludGYoc3RkZXJyLCAiTnVtZXJvIGludsOhbGlkby4gQWJvcnRhbmRvIGV4ZWN1w6fDo28uXG4iKTsKICAgIGV4aXQoMSk7CiAgfQogIAogIHByaW50ZigiU3RyaW5nOiBbJXNdXG4iLCBzdHIpOwogIHByaW50ZigiRmxvYXQ6ICVmXG4iLCBmKTsKfQoKaW50IGdldF9zdHJpbmcoY2hhciAqcHJvbXB0LCBjaGFyICpzdHIsIHNpemVfdCBzaXplKSB7CiAgcHJpbnRmKCIlcyIsIHByb21wdCk7CiAgZmdldHMoc3RyLCBzaXplICsgMSwgc3RkaW4pOwoKICAvKiBSZW1vdmUgXG4gKi8KICBmb3IgKGNoYXIgKnBzdHIgPSBzdHI7ICpwc3RyICE9ICdcMCc7ICpwc3RyKyspIHsKICAgIGlmICgqcHN0ciA9PSAnXG4nKSB7CiAgICAgICpwc3RyID0gJ1wwJzsKICAgICAgYnJlYWs7CiAgICB9CiAgfQp9CgppbnQgZ2V0X2Zsb2F0KGNoYXIgKnByb21wdCwgZmxvYXQgKnB2YWwpIHsKICBzdGF0aWMgY2hhciBzdHJbTUFYRkxPQVRMRU4gKyAxXTsKICAKICBwcmludGYoIiVzIiwgcHJvbXB0KTsKICBmZ2V0cyhzdHIsIE1BWEZMT0FUTEVOICsgMSwgc3RkaW4pOwogIHJldHVybiBzc2NhbmYoc3RyLCAiJWYiLCBwdmFsKTsKfQo="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>

/* Prototypes */
int get_string(char *prompt, char *str, size_t size);
int get_float(char *prompt, float *val);

/* Maior tamanho de uma linha de entrada (float) */
#define MAXFLOATLEN 32

/* Maior tamanho do string */
#define MAXSTRINGLEN 10

int main() {
  int ret;
  float f;
  char str[MAXSTRINGLEN + 1];
  
  get_string("Enter string: ", str, sizeof(str));
  
  if (get_float("Entre um valor em ponto-flutuante", &f) != 1) {
    fprintf(stderr, "Numero inválido. Abortando execução.\n");
    exit(1);
  }
  
  printf("String: [%s]\n", str);
  printf("Float: %f\n", f);
}

int get_string(char *prompt, char *str, size_t size) {
  printf("%s", prompt);
  fgets(str, size + 1, stdin);

  /* Remove \n */
  for (char *pstr = str; *pstr != '\0'; *pstr++) {
    if (*pstr == '\n') {
      *pstr = '\0';
      break;
    }
  }
}

int get_float(char *prompt, float *pval) {
  static char str[MAXFLOATLEN + 1];
  
  printf("%s", prompt);
  fgets(str, MAXFLOATLEN + 1, stdin);
  return sscanf(str, "%f", pval);
}