Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Programação de Computadores IIAula 10. Bibliotecas e String
Slides cedidos por Karina Mochetti
2018.1
Aula 10. Bibliotecas e String
Bibliotecas
Biblioteca é uma conjunto de subprogramas utilizados naprogramação que contém código e dados auxiliares externos aoprograma principal, o que permite o compartilhamento e aalteração de código e dados de forma modular.
/* Hello World program */
#include<stdio.h>
int main() {
printf ("Hello World.\n");return 0;
}
Aula 10. Bibliotecas e String
Cabeçalhos
Cabeçalhos (ou headers) são intermediários entre o programaprincipal e cada módulo. Ele contém somente a declaração detodas as funções com comentários bem detalhados de cada uma.
Aula 10. Bibliotecas e String
Biblioteca math.h
De�ne funções matemáticas utilizando o tipo double.
double cos(double x);
double sin(double x);
double tan(double x);
double exp(double x);
double log(double x);
double pow(double x, double y);
double sqrt(double x);
double fabs(double x);
Aula 10. Bibliotecas e String
Biblioteca math.h
#include<math.h>
int main () {
double angulo = 1.04716; // 60 em radianos
double coseno, seno, tangente;
coseno = cos(angulo):
seno = sin(angulo);
tangente = tan(angulo):
return 0;
}
Aula 10. Bibliotecas e String
Biblioteca time.h
De�ne funções de tempo criando tipos próprios para isso.
struct tm: tm_sec, tm_min, tm_hour, tm_mday, tm_mon,tm_year, tm_wday, tm_yday, tm_isdst
typedef time_t
time_t time();
struct tm *localtime(time_t *t);
char *asctime(struct tm t);
double di�time (struct tm t1, struct tm t2);
Aula 10. Bibliotecas e String
Biblioteca time.h
#include<time.h>
int main () {
cha *str;
time_t tempo_inteiro;
struct tm tempo_dividido;
tempo_inteiro = time();
tempo_dividido = localtime(&tempo_inteiro);
str = asctime(tempo_dividido);
return 0;
}
Aula 10. Bibliotecas e String
Biblioteca limits.h
De�ne propriedades de alguns tipos pré-de�nidos em C.
#de�ne CHAR_MAX 127;
#de�ne UCHAR_MAX 255;
#de�ne INT_MIN -2,147,483,648;
#de�ne INT_MAX 2,147,483,647;
#de�ne UINT_MAX 4,294,967,295;
Aula 10. Bibliotecas e String
Biblioteca limits.h
#include<limits.h>
int main() {
unsigned int i;
int j = INT_MAX;
for (i = 0; i < UINT_MAX; i++)
j--;
return 0;
}
Aula 10. Bibliotecas e String
Biblioteca stdio.h
De�ne rotinas de entrada e saída padrão e de arquivos.
int printf ( const char * format, ... );
int scanf ( const char * format, ... );
FILE * fopen ( const char * �lename, const char * mode );
int fclose ( FILE * stream );
size_t fread ( void * ptr, size_t size, size_t count, FILE *stream );
size_t fwrite ( const void * ptr, size_t size, size_t count,FILE * stream );
streams padrões: stdin, stdout, stderr
Aula 10. Bibliotecas e String
Biblioteca stdio.h
#include<stdio.h>
int main() {
int n;
char c;
float f;
printf("Lendo 3 variaveis: ");
scanf("%d %c %f", &n, &c, &f);
printf("Escrevendo 3 variáveis: %f %c %d", f, c, n);
return 0;
}
Aula 10. Bibliotecas e String
Biblioteca string.h
De�ne rotinas para manipulação de strings, que são vetores de char.
char *strcat(char *dest, const char *src);
int strcmp(char *str1, char *str2)
void strcpy(char *dest, const char *src);
size_t strlen(char *str);
char nome[256];char *nome;
Aula 10. Bibliotecas e String
Strings
Não há o tipo String em C, Strings são vetores de caracteres!
Toda string em C termina com um caracter especial, o \0.String são descrita entre aspas duplas " e caracteres entreaspas simples '.
char nome[12] = "Hello World";char *nome = "Hello World";
Aula 10. Bibliotecas e String
Tabela ASCII
Aula 10. Bibliotecas e String
Caracter como Inteiro
Em C o tipo de cada variável é mais livre.
Como visto na Tabela ASCII todo caracter é na verdade umnúmero da tabela.
#include <stdio.h>
int main() {
char c = 'd';
printf("O caracter é: %c \n", c);
printf("Seu número na tabela ASCII é: %d \n", c);
printf("O próximo caracter na tabela é: %c \n", c+1);
return 0;
}
Aula 10. Bibliotecas e String
Caracter '\n'
O caracter '\n' é um caracter especial que indica quebra delinha.
Na saída padrão é sempre usado o '\n', mas em arquivos háuma diferença entre SO.
Linux e Mac: '\n'Win: '\r \n'
Aula 10. Bibliotecas e String
Caracter '\0'
O caracter '\0' indica o �m de uma String em C.
Uma string de n letras precisará de n + 1 espaços na memória.
Ao ler uma string com "%s", o compilador adiciona o caracter'\0' sozinho.Ao atribuir uma string com aspas ", o compilador adiciona ocaracter '\0' sozinho.Para se usar as funções de string, é preciso que o '\0' estejapresente.
Aula 10. Bibliotecas e String
Casting
Em C é possível "traduzir" uma variável de um tipo para outroa qualquer momento.
Isso é chamado de casting, mas é algo que deve ser feito comcuidado já que tipos diferentes possuem limites einterpretações diferentes de uma variável.
#include <stdio.h>
int main() {
int i = 10;
float f;
f = (float) i;
return 0;
}
Aula 10. Bibliotecas e String
Exemplo 1
Escreva um programa que imprima a tabela ASCII:
#include <stdio.h>
int main() {
for (int i = 0; i<128; i++)
printf("%d -> %c \n", i, i);
return 0;
}
Aula 10. Bibliotecas e String
Exemplo 2
Ler e comparar duas strings:
#include <stdio.h>
#include <string.h>
int main() {
char *str1, str2;
scanf ("%s", str1);
scanf ("%s", str2);
if (strcmp (str1, str2) == 0)
printf ("Sao diferentes\n");
else
printf ("Sao iguais\n");
return 0;
}
Aula 10. Bibliotecas e String
Exemplo 3
Dividir dois inteiros resultando num �oat:
#include <stdio.h>
#include <string.h>
int main() {
int m, n;
float f;
scanf ("%d %d", &n, &m);
f = (float) m / (float) n;
printf("O resultado e %f\n", f);
return 0;
}
Aula 10. Bibliotecas e String
Exercício
Escreva um programa que dado um caracter qualquer, imprime oscaracteres anterior e posterior a ele na tabela ASCII e o seu númeroem hexadecimal na tabela.
Exemplos:
b → a c 98
0 → / 1 48
) → ( * 41
Aula 10. Bibliotecas e String