User input not being passed to function - c

I am working on a college project and we're supposed to write a basic CRUD program in C. In case 1 of my switch, "cpfinput" is passed fine to my function inserir_servidor, but "nominput" (name) is not. I tried debugging it and nominput does actually contain the user input, but when I print my "nomes" array after calling the function, it's empty.
Please forgive me if this is a poorly written post, I am new to SO.
How to reproduce:
1 - Type 1 and press enter.
2 - Enter anything.
3 - Enter anything.
4 - Type 5, it should display "0, a blank, and whatever your inserted in step 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAM 100
char codigos[TAM][9];
char nomes[TAM][255];
char cpfs[TAM][11];
int ocupados[TAM];
int inserir_servidor(char[], char[]);
int alterar_servidor(char[], char[], char[]);
int excluir_servidor(char[]);
int mostrar_servidor(char[]);
int mostrar_servidores();
void inic_ocupados();
int main()
{
char codinput[9], nominput[255], cpfinput[11];
int input = -1;
inic_ocupados();
do
{
printf("1. Inserir um servidor.\n");
printf("2. Alterar um servidor.\n");
printf("3. Excluir um servidor.\n");
printf("4. Mostrar um servidor.\n");
printf("5. Mostrar todos os servidores.\n");
printf("0. Sair do programa.\n");
printf("Escolha: ");
scanf("%d", &input);
switch(input)
{
case 0:
printf("Encerrando...");
return 0;
case 1: //inserir
printf("Insira o nome do servidor: ");
scanf(" %s", nominput);
printf("Insira o cpf do servidor: ");
scanf(" %s", cpfinput);
inserir_servidor(nominput, cpfinput);
break;
case 2: //alterar
printf("Insira o codigo do servidor: ");
scanf(" %s", codinput);
printf("Insira um novo nome: ");
scanf(" %s", nominput);
printf("Insira um novo cpf: ");
scanf(" %s", cpfinput);
alterar_servidor(codinput, nominput, cpfinput);
break;
case 3: //excluir
printf("Digite o codigo do servidor a ser excluido: ");
scanf(" %s", codinput);
excluir_servidor(codinput);
break;
case 4: //listar um
printf("Digite o codigo do servidor a ser mostrado: ");
scanf(" %s", codinput);
mostrar_servidor(codinput);
break;
case 5: //listar todos
mostrar_servidores();
break;
default:
printf("Escolha invalida.\n");
break;
}
} while(input);
return 0;
}
int inserir_servidor(char nominput[], char cpfinput[])
{
for(int i = 0; i < TAM; i++)
{
if (!ocupados[i])
{
itoa(i, codigos[i], 10);
strcpy(nomes[i], nominput);
strcpy(cpfs[i], cpfinput);
ocupados[i] = 1;
return 1;
}
}
return 0;
}
int alterar_servidor(char codinput[], char nominput[], char cpfinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!strcmp(codigos[i], codinput))
{
strcpy(nomes[i], nominput);
strcpy(cpfs[i], cpfinput);
return 1;
}
}
return 0;
}
int excluir_servidor(char codinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!strcmp(codigos[i], codinput))
{
ocupados[i] = 0;
return 1;
}
}
return 0;
}
int mostrar_servidor(char codinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!ocupados[i])
{
if(!strcmp(codigos[i], codinput))
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
return 1;
}
}
}
return 0;
}
int mostrar_servidores()
{
for(int i = 0; i < TAM; i++)
{
if(ocupados[i])
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
}
}
return 0;
}
void inic_ocupados()
{
for(int i = 0; i < TAM; i++)
{
ocupados[i] = 0;
}
}

I cannot find the error you report.
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha: 1
Insira o nome do servidor: aaaaa
Insira o cpf do servidor: bbbbb
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha: 5
Codigo Nome CPF
0 aaaaa bbbbb
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha:
There are multiple errors in the code.
First scanf(" %s",... looks for space delimted input so if I enter this
Escolha: 1
Insira o nome do servidor: mr smith <<<<<=========
Insira o cpf do servidor: 1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha:
The 'mr' is taken as 'nom' and 'smith' is taken as 'cpf'
Also this function
int mostrar_servidor(char codinput[])
{
for (int i = 0; i < TAM; i++)
{
if (!ocupados[i])
{
if (!strcmp(codigos[i], codinput))
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
return 1;
}
}
}
return 0;
}
Is broken.
It only looks at unoccupied cells
if (!ocupados[i])
should be
if (ocupados[i])

Related

a matrix not printing correctly in c

I don't know why mat[7][8]='A' prints A in the whole column. The procedure is a game grid where we should put pions of gamers and maintain all their previous pions on the grid. I don't know why changing the value of this matrix outside a for loop doesn't do anything right as it supposed to be.
Here is the code:
#include "Go_1.h"
#define DIMENSION 9
#define SPACELEFT 2
/* cette donction permet d'affichier la matrice à l'état initial, de placer le pion du joueur à
l'intersection en analysant si la place est vide ou pas, et d'afficher la grille avec les pions
des joueurs*/
void grille(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char *joueur,char lettres[],char nombres[])
{
int a=0; /* servira de compteur pour afficher tous les caracteres de A--I en utilsant le code ASCII*/
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;/* = 25// nb de lignes et colonnes où
on doir afficher les valeurs de la matrice stockées dans LIGNE_COLONNE(25) lignes et colonnes*/
printf("\t");
printf(" "); /*2 spaces*/
/*affichage des lettres délimitant le goban horizontalement*/
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
/*Remplissage de la matrice*/
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
/*affichage des nombres délimitant le goban verticalement*/
for (int i=0;i<LIGNE_COLONNE;i++) /* LIGNE_COLONNE in this case= 25*/
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0)) /* le cas où mat[i][j] est une intersection*/
{
/*if (i==*x && j==*y) /*tester si les indices coincident avec ceux choisis par le joueur
{
if (mat[*x][*y]=='0') /*tester si l'intersection ets vide cad contient '0'*
{
mat[*x][*y]=jeton;
}
else
{
printf("\tLa place est deja occupee!");
choix_pion(joueur,jeton,x,y,lettres,nombres);/*on lui demande de réexprimer
son choix où placer son pion
break;
}
} */
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return;
}
Well, I refactored the code a bit and I get the following output:
A B C D E F G H I
Since I did not know how to define TAILLE_MATRICE I just assigned 64
That's the code for anyone wanting to try it out:
#include<stdio.h>
#define DIMENSION 9
#define SPACELEFT 2
#define TAILLE_MATRICE 64
int main(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char
*joueur,char lettres[],char nombres[])
{
int a=0;
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;
printf("\t");
printf(" ");
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
for (int i=0;i<LIGNE_COLONNE;i++)
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0))
{
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return 0;
}

(C Language) Only show filled entries in list

I hope this will be the last time I ask something here. Everything in my Food Ordering Algorithm is finished, but showing the list of filled orders shows every slot available (0 to 100), rather than just the entries filled out. Any way to fix that?
Case 3: Shows all orders made. (But I want just the entries that are filled out, not the empty ones.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAM 100
typedef struct order
{
char nome[50];
char endereco[150];
char pedido[300];
char valor[10];
};
int main()
{
struct order lista[TAM];
int busca, acha, i, menu;
i = 0;
menu = 0;
int codigo = 0;
int c = 0;
while(menu != 4)
{
system("cls");
printf("====================\n");
printf("Selecione uma opcao\n");
printf("====================\n");
printf("1 - Cadastrar pedido\n");
printf("2 - Consultar pedido\n");
printf("3 - Emitir relatorio\n");
printf("4 - Sair\n");
scanf("%d", &menu);
fflush(stdin);
switch(menu)
{
case 1:
system("cls");
printf("Digite seu nome: \n");
scanf("%49[^\n]", lista[i].nome);
fflush(stdin);
printf("Digite seu endereco: \n");
scanf("%149[^\n]", lista[i].endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
scanf("%299[^\n]", lista[i].pedido);
fflush(stdin);
printf("Digite o valor total: \n");
scanf("%9[^\n]", lista[i].valor);
fflush(stdin);
system("cls");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
system("pause");
i = i + 1;
codigo = codigo + 1;
break;
case 2:
system("cls");
printf("Insira o codigo que deseja buscar:\n");
scanf("%d", &busca);
fflush(stdin);
if(busca < codigo)
{
printf("=============================\n");
printf("Codigo: %d\n", busca);
printf("Nome: %s\n", lista[busca].nome);
printf("Endereco: %s\n", lista[busca].endereco);
printf("Pedido: %s\n", lista[busca].pedido);
printf("Valor total: %s\n", lista[busca].valor);
printf("=============================\n");
system("pause");
}
else
{
printf("\n Codigo nao encontrado\n");
system("pause");
break;
}
break;
case 3:
system("cls");
c = 0;
for(i = 0; i < TAM; i++){
printf("=============================\n");
printf("Codigo: %d\n", c);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
c = c + 1;
}
system("pause");
break;
case 4:
return 0;
default:
printf("Opcao invalido\n");
system("pause");
}
}
return 0;
}
change
for(i = 0; i < TAM; i++){
to
for(i = 0; i < codigo ; i++){
codigo is the count og entrries, TAM is the max number of entries

Can't input new order

Okay, hopefully after this, I won't ask anymore questions here. I redid the entire code, replacing gets() with scanf(). Now though, whenever I choose to put a new order for the program, I just put the name and the process just ends, showing "return value 3221225477", preventing me from typing in the address, request and price. I screwed up somewhere, but I don't know what. Here's what I did:
Translation:
Case 1: Type name, address, order, total price.
Case 2: Search for code (Issue: new string overwrites old one constantly)
Case 3: Show list of all orders created.
Case 4: Exit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAM 100
struct order
{
char nome[50];
char endereco[150];
char pedido[300];
char valor[10];
};
int main()
{
struct order lista[TAM];
int busca, acha, i, menu;
menu = 0;
int codigo = 0;
int c = 0;
while(menu != 4)
{
system("cls");
printf("====================\n");
printf("Selecione uma opcao\n");
printf("====================\n");
printf("1 - Cadastrar pedido\n");
printf("2 - Consultar pedido\n");
printf("3 - Emitir relatorio\n");
printf("4 - Sair\n");
scanf("%d", &menu);
fflush(stdin);
switch(menu)
{
case 1:
system("cls");
printf("Digite seu nome: \n");
scanf("%49[^\n]", lista[i].nome);
fflush(stdin);
printf("Digite seu endereco: \n");
scanf("%149[^\n]", lista[i].endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
scanf("%299[^\n]", lista[i].pedido);
fflush(stdin);
printf("Digite o valor total: \n");
scanf("%9[^\n]", lista[i].valor);
fflush(stdin);
system("cls");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
system("pause");
i = i + 1;
codigo = codigo + 1;
break;
case 2:
system("cls");
printf("Insira o codigo que deseja buscar:\n");
scanf("%d", &busca);
fflush(stdin);
i = 0;
acha = 0;
while(i < TAM && acha == 0)
{
if(codigo == busca)
{
acha = 1;
}
else
{
i = i + 1;
codigo = codigo + 1;
}
if(acha == 1)
{
printf("=============================\n");
printf("Codigo: %d\n", codigo);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
system("pause");
}
else
{
printf("\n Codigo nao encontrado\n");
system("pause");
break;
}
}
break;
case 3:
system("cls");
c = 0;
for(i = 0; i < TAM; i++){
printf("=============================\n");
printf("Codigo: %d\n", c);
printf("Nome: %s\n", lista[i].nome);
printf("Endereco: %s\n", lista[i].endereco);
printf("Pedido: %s\n", lista[i].pedido);
printf("Valor total: %s\n", lista[i].valor);
printf("=============================\n");
c = c + 1;
}
system("pause");
break;
case 4:
return 0;
default:
printf("Opcao invalido\n");
system("pause");
}
}
return 0;
}
well the immediate cause is this
int busca, acha, i, menu; <<<<=== declare i , but not set to a value
....
scanf("%49[^\n]", lista[i].nome); <<<==== use i
you must set i to zero
int i = 0;

Is there any way to make the scanf() function ignore invalid characters?

So, I've made this code, and it works wonderfully, but the problem is that I've got some scanf functions only accepting numbers, and some others only accepting characters, but for example, when I input a character on a scanf that requires an int value, the program behaves really unexpectedly, doing stuff such as repeating the same printf all over the command prompt, or repeating it thrice.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int descuento(int num, int descuento);
int rangoValido(int Rangomin, int Rangomax, int i);
int numeroRandom();
int sino(char sino);
int main(void){
int productoid[1000][1];
int idprompt;
int descuento25[14] = {398, 309, 281, 948, 19, 67, 187, 80, 889, 482, 566, 24, 87, 98};
int descuento15[14] = {992, 788, 987, 90, 155, 596, 27, 587, 98, 273, 344, 69, 89, 234};
char respuesta;
int listacompra[100][1];
int precio;
int colector = 0;
int comprobante = 0;
int total;
int monto;
//Si la id del producto no esta dentro del rango valido, el bloque se repite
do{
do{
do{
printf("Escriba la ID del producto: ");
scanf("%d", &idprompt);
}
while(0==rangoValido(1,1000,idprompt));
//Una vez comprobada la validez del numero ingresado, se crea un numero aleatorio que se le
asigna para el precio, idprompt es la misma id
comprobante = 0;
srand(idprompt);
productoid[idprompt][1]=numeroRandom();
printf("ID del producto: %d\n", idprompt);
printf("Precio del producto: %d\n", productoid[idprompt][1]);
precio = productoid[idprompt][1];
//Comprobacion de descuentos
for(int i=0; i<=14; i++){
if(descuento25[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],25);
printf("Descuento del producto: 25\n");
}else{
if(descuento15[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],15);
printf("Descuento del producto: 15\n");
}
}
}
//Anadiendo el producto al carro de compras y comprobando la respuesta
do{
printf("Quieres anadir este producto a tu carrito de compras? (Y/N) ");
scanf(" %c", &respuesta);
}while(2 == sino(respuesta));
}while(respuesta == 'n' || respuesta == 'N');
if(respuesta == 'y' || respuesta == 'Y'){
listacompra[colector][0] = idprompt;
listacompra[colector][1] = precio;
colector = colector + 1;
}
do{
printf("Quieres seguir comprando? (Y/N) ");
scanf(" %c", &respuesta);
printf("\n");
if(0 == sino(respuesta)){
for(int i=0; i<colector; i++){
printf("\nID del producto %d: %d\n", i+1, listacompra[i][0]);
printf("Precio del producto %d: %d\n", i+1, listacompra[i][1]);
}
}
if(1==sino(respuesta)){
comprobante = 1;
}
}while(2==sino(respuesta));
}while(comprobante==1);
for(int i=0; i<colector; i++){
total = total + listacompra[i][1];
}
printf("\n\nTotal a pagar: %d\n", total);
printf("Ingrese monto recibido: ");
scanf("%d", &monto);
printf("\n");
if(monto<total){
printf("%d faltantes.", total-monto);
}
if(monto>=total){
printf("Vuelto: %d", monto-total);
}
return 0;
}
int numeroRandom(){
int random;
random = rand();
if(random>3000 && random<10000){
random = random / 5;
}
if(random<100){
random = random * 3;
}
if(random>10000){
random = random / 13;
}
return random;
}
int rangoValido(int Rangomin, int Rangomax, int i){
if(i>=Rangomin && i<=Rangomax){
return 1;
}else{return 0;}
}
int descuento(int num, int descuento){
num = num * (descuento / 100);
return num;
}
//Si la funcion sino() regresa 0, entonces la respuesta fue no. Si es 1, la respuesta es si. Y si
es 2, la respuesta es invalida.
int sino(char sino){
if(sino=='y' || sino=='Y'){
return 1;
}
if(sino=='n' || sino=='N'){
return 0;
}
else{return 2;}
}

Problems in the for loop in language C

The program compiles perfectly, the problem is the cycle, it does not show me the position
here goes the include of library stdio.h
int main(void)
{ int x, i=0,j=0, a[100];
char sal;
printf("Este programa lee un arreglo de numeros enteros y un numero x, y muestra en pantalla los indices de las posiciones en donde se encuentra ese numero x\n");
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
i++;
printf("Si desea salir presione s: ");
scanf(" %c", &sal);
}while(sal!='s');
printf("Ingrese el valor de la variable x: ");
scanf("%i", &x);
for (j; j<=i; j++)
{
if(a[i]==x)
printf("%i",i);
}
printf("\n");
}
You condition of the for loop should be j<i, not j<i+1. When the while
loop exits, i has the value for the next input, but it has not been set because
the loop exited.
Also you are using the index i instead of j in the for-loop. j is the
running index, not i:
for (j; j<i; j++)
{
if(a[j]==x)
printf("%i", j);
}
would be correct.
Your while loop is ok, but a bit clunky. First you don't check if you are
writing past the limit of a. The conditions should be
while(sal!='s' && i < (sizeof a / sizeof *a));
so that the user cannot input more values than a can hold.
The way you exit the loop is also awkward, the user has to type something
different to s to continue and it can only be one character. This would be
better:
int c;
char line[100] = { 0 };
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
while((c = getchar()) != '\n' && c != EOF); // to clear the input buffer
i++;
printf("Si desea salir ingrese SALIR. Para continuar presione ENTER: ");
fgets(line, sizeof line, stdin);
} while(strcmp(line, "SALIR\n") && strcmp(line, "salir\n") && i < (sizeof a / sizeof *a));
Note that strcmp returns 0 when the strings are equal, a non-zero otherwise.
A tip, you should always set the loop counter to 0 either right before the loop, or in the loop. And it's always a good practice to initialize all variables during declarations. In your case, you did not initialize integer array. Below is a modified version of your code.
int main(void)
{
int x, i, j;
x = i = j = 0;
int a[100] = { 0 };
char sal = 0;
printf ("Este programa lee un arreglo de numeros enteros y un numero x, "
"y muestra en pantalla los indices de las posiciones en donde se "
"encuentra ese numero x\n");
while(1)
{
printf("Ingrese un numero: ");
scanf("%d", &a[i]);
i++;
printf("Si desea salir presione s: ");
scanf(" %c", &sal);
if (sal == 's')
break;
}
printf("Ingrese el valor de la variable x: ");
scanf("%d", &x);
for (j = 0; j <= i; j++)
{
if (a[i] == x)
printf("%d", i);
}
printf("\n");
}

Resources