Hi, I don't know why I need to use two getc(stdin).
Some people said me it was a newline in the buffer and I shouldn't use scanf().
Why shouldn't I? How would you write this code in other/better way without using scanf() and 2 getc(stdin)?
Thank you.
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 50 51 52 53 54
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/*
*
*/
int main(int argc, char** argv) {
int opt;
printf("1. Inserir\n");
printf("2. Consultar\n");
scanf("%d",&opt);
switch(opt){
case 1:
inserir();
break;
case 2:
consultar();
break;
}
}
inserir() {
FILE *escrita;
char nome[20];
char tel[15];
char q = 'y';
int i=0;
if ((escrita = fopen("telefones.txt","w")) == NULL ) {
perror("File");
exit(1);
}
while ( q != 'n' && q != 'N' ) {
printf("Nome: ");
scanf("%s",nome);
while(nome[i]){
q = nome[i];
nome[i] = toupper(q);
i++;
}
printf("Telefone: ");
scanf("%s",tel);
fprintf(escrita,"%s %s\n",nome,tel);
getc(stdin);
q = getc(stdin);
}
fclose(escrita);
}
consultar() {
}
|
Last edited on
i think its fine to use scanf?? or getc..
they are not very secure function thats why compiler warn you about that, otherwise not a problem.
insecure in the sense a buffer overflow can compromise the security of your program.
scanf and getc only. what else you can use. you don't have to worry much.
if you work on windows then microsoft has created secure versions of all these functions like scanf_s etc etc.. _s mean secure versions.
You are doing fine.
The better alternative, if you want it, is to simply read a line of input then scan it for formatted data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <stdio.h>
#include <string.h>
int main()
{
char user_input[ 100 ];
char nombre[ 20 ];
unsigned edad = 0;
printf( "Cual es tu nombre? " );
fgets( user_input, sizeof(user_input), stdin );
*nombre = 0;
strcat( nombre, user_input, sizeof(nombre)-1 );
printf( "Hola, %s!\nCuantos anos tienes? ", nombre );
fgets( user_input, sizeof(user_input), stdin );
sscanf( user_input, "%u", &edad );
if (edad < 25)
printf( "Caray! Solo tienes %u anos! Uau!\n" );
else
printf( "Este... mi mas sentido pesame. Solo peora desde hoy... (viajito)\n" );
}
|
If you can, I recommend you use the
GNU Getline function
http://www.gnu.org/software/hello/manual/libc/Line-Input.html
Hope this helps.
[edit] You can also use
atoul() and the like to avoid *scanf.
Last edited on