Related
I have a problem with my code:
When I write any input different from 1,2,3,4 the output is
Inserire il numero dei giocatori
inserire un numero valido
Inserire il numero dei giocatori
inserire un numero valido
Inserire il numero dei giocatori
How can I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
int controll_num(){
int controll=0;
int players;
char c;
do{
printf("Inserire il numero dei giocatori \n");
c=getc(stdin);
switch (c){
case 49:
players=1;
controll=1;
break;
case 50:
players=2;
controll=1;
break;
case 51:
players = 3;
controll=1;
break;
case 52:
players = 4;
controll=1;
break;
default:
printf("inserire un numero valido\n");
}
}while(controll==0);
return players;
}
int main(){
controll_num();
return 0;
}
Instead of getc use scanf as for example
scanf( " %c", &c );
Pay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character '\n' that is placed in the input buffer by pressing the Enter key.
As for getc then it can read white space characters.
Also instead of using magic numbers like 49 as case labels
case 49:
use characters like
case '1':
This will make your code more readable.
You need to check if the value is digit and your switch case is not needed at all.
int controll_num(void){
int players;
char c;
while(1)
{
printf("Inserire il numero dei giocatori \n");
c=getc(stdin);
if(isdigit((unsigned char)c))
{
players = c - '0';
break;
}
printf("inserire un numero valido\n");
};
return players;
}
int main(void)
{
printf("Number of players %d\n", controll_num());
}
https://godbolt.org/z/sf7nxE7cx
I have to save three different strings in n number of 2D arrays, for that reason I created a 3D array named datosCliente[size][4][size]. After that I have to print their content. But when I'm printing the strings in the first and second string the first character disappear, and the third string isn't printed.
The first string is the name of a country.
The second is the date of departure.
The last is the date of return.
This is the code:
#include <stdio.h>
#include <stdlib.h>
const int size = 100;
void ingresoDatos(char [size][4][size], int*);
void imprimirDatos(char [size][4][size], int*);
int main(void) {
char datosCliente[size][4][size];
int cant;
FILE *document;
document = fopen("data.txt", "a");
if(document == NULL) {
printf("Error al abrir el archivo.\n");
}else {
ingresoDatos(datosCliente, &cant);
imprimirDatos(datosCliente, &cant);
}
fclose(document);
return 0;
}
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
printf("Ingrese el número de clientes: ");
scanf("%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
getchar();
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
getchar();
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
getchar();
}
}
void imprimirDatos(char datos[size][4][size], int *cant) {
system("clear");
for(int i = 1; i <= *cant; i++) {
printf("Cliente %d:\n", i+1);
printf("Destino: %s", &datos[i][0][100]);
printf("Fecha de salida: %s", &datos[i][1][100]);
printf("Fecha de regreso: %s", &datos[i][2][100]);
printf("\n");
}
}
I enter this data:
tam: 1
Destino (to): China
Fecha de salida (depart in): 23 de septiembre de 2022
Fecha de regreso (return in): 24 de noviembre de 2022
And this is the output:
Cliente 1:
Destino: hina
Fecha de salida: 3 de septiembre de 2022
Fecha de regreso:
I had forgotten mention but I'm using Replit to do the code.
scanf("%d", &tam); doesn't consume a newline character even if it is entered. (c - fgets doesn't work after scanf - Stack Overflow) In my opinion, you shouldn't mix scanf() and fgets(). You can use fgets() to read a line and sscanf() to parse the line.
fgets() consumes a newline character (if it is entered). Calling getchar(); after that will drop the first character of the next line.
Considering these points, the function ingresoDatos should be:
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
char buffer[100];
printf("Ingrese el número de clientes: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
}
}
Hello I'm fairly new to programming so here's my problem, I have multiple arrays of the size x,
I want to add b values to my array, what I did is x + b then ask the user to type his value then call a function that looks if the value is already in the array, if it is, I ask the user to type it again, but the problem is that the search function returns random numbers. heres my code (the fRecherche2 works fine outside of fAjouter):
int fRecherche2 (int ref[],int n,int nref)
{
int i;
for (i=0;i<n;i++)
if (ref[i]==nref)
return i;
return -1;
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,prods,nb,code,nref;
printf("How many products would you like to add:");
scanf("%d",& prods);
fVerifVal(prods);
n=NbArticle();
nb=n+prods;
for(i=n;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d\n",code);
while(code!=-1)
{
printf("The reference already exists.\n");
printf("Please try again: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d",code);
if(code==-1)
break;
}
fVerif(ref,i); //Checks if the value is bigger than 0
printf("Amount: ");
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Price: ");
scanf("%f", &prix[i]);
fVerifReal(prix,i); //Checks if the value is bigger than 0.00
printf("Security threshold: ");
scanf("%d", &sds[i]);
fVerif(sds,i);
}
fEnregNombre(nb); //saves my new size in a file
code=fEnreg(ref,qt,prix,sds,nb); // saves all my new arrays in a file
if(code==-1)
return -1;
}
void fCreerStock (void)
{
int i,n;
printf("Combien d'articles : ");
scanf("%d", &n );
while(n<=1)
{
printf("Il faut au moins 1 article!\n");
printf("Veuillez réesayer: ");
scanf("%d",&n);
if(n>0)
break;
}
FILE * nombre;
nombre=fopen("Nombre_d'article.txt","w");
if (nombre == NULL)
{
printf("probleme d'ouverture du fichier \n");
exit(1);
}
fprintf(nombre,"%d",n);
fclose(nombre);
int ref[n],qt [n], sds [n];
float prix[n];
for (i=0; i<n; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref[i]);
fVerif(ref,i);
printf("quantité %d : ", i);
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Prix %d : ", i);
scanf("%f", &prix[i]);
fVerifReal(prix,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds[i]);
fVerif(sds,i);
}
FILE * flot;
flot=fopen("nom.txt","a");
if (flot == NULL)
{
printf("Probleme d'ouverture du fichier \n");
exit(1);
}
for (i=0; i<n; i++)
fprintf(flot,"%d\t%d\t%.2f\t%d\n",ref[i],qt[i],prix[i],sds[i]);
fclose(flot);
}
#include <stdio.h>
#include "sae.h"
void globale (void)
{
int n;
n=NbArticle();
int ref[n],qt[n],sds[n],CodeErr,code,CodeSup;
float prix[n];
char choix;
CodeErr=fConsulterStock(ref,qt,prix,sds,n);
printf("\n\nBienvenue a l'application de gestion de stock 'Xtrachaus'\n\n");
if (CodeErr== -1 || n == -1)
printf("!! Vous n'avez pas encore créer de stock veuillez créer un stock avant de faire n'importe quel manipulation !! \n\n");
printf("Créer un stock: 'c'| Afficher le stock: 'o'| Etat du stock: 'e'| Faire le devis d'une commade: 'd'| Récapitulatif des ventes: 'r'| Approvisionnement: 'a'| \nSupprimer un article:'s'| Rechercher un article avec n° ref: 'n'| Modifier l'article :'m'| Ajouter un article: 't'\n\n");
printf("Que voulez vous faire(votre choix): ");
scanf("%c%*c", &choix);
if (choix =='c')
fCreerStock();
if (choix =='o')
fAfficherStock(ref,qt,prix,sds,n);
if (choix =='e')
fEtatStock(ref,qt,prix,sds,n);
/*if (choix =='d')
fDevis();
if (choix =='r')
fVentes();*/
if (choix =='a')
{
fAfficherStock(ref,qt,prix,sds,n);
code=fAppro(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'approvisionement ne peut pas s'effectuer.\n");
else
printf("Approvisionement éffectué. \n");
printf("\n");
fAfficherStock(ref,qt,prix,sds,n);
}
if (choix =='s')
{
CodeSup=fSuppression(ref,qt,prix,sds,n);
if(CodeSup!=-1)
printf("Suppression éffectué. \n");
else
printf("Erreur, la suppression ne peut pas s'effectuer.\n");
}
if (choix =='n')
{
code=fRecherche(ref,n);
if (code!=-1)
{
printf("\nReference:\tQuantite:\tPrix:\tSeuil de securite:\n");
printf("%d\t\t%d\t\t%.2f\t\t%d\n" ,ref[code], qt[code], prix[code], sds[code]);
}
else
printf("La réference n'existe pas\n");
}
if (choix =='t')
{
code==fAjouter(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'ajout ne peut pas s'effectuer.\n");
else
printf("Ajout éffectué. \n");
}
if (choix =='m')
{
code=fModifier(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, la modification ne peut pas s'effectuer.\n");
else
printf("Modification éffectué. \n");
}
}
int main (void)
{
globale();
return 0;
}
If theres anything else I could provide please tell me! Thanks.
(sorry most of the code and variables are in french i translated the part im stuck at).
edit3:
heres examples of where the program fails:
before adding a value:
https://imgur.com/XRbXvVl
After:
https://i.imgur.com/mRI1aJq.png (i choose 't' to add a value then type the how many i want to add, in this picture i wanted 1 more value, but i don't get to type my information, it immeadiatly adds random values)
https://imgur.com/HJk1PaW
One major problem: In the fAjouter function you have code like this
n=NbArticle();
nb=n+prods;
for(i=n+1;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
...
}
The array ref have n elements, and in the loop you start its indexing with n + 1.
Unless prods is equal to zero then i will start out of bounds of the array, and using it as an index will lead to undefined behavior.
Remember that array-size in C is fixed once the array is defined. C doesn't have dynamic arrays. If you need dynamic arrays whose size can be extended you need to use dynamic allocation with e.g. malloc and realloc.
I solved my problem by creating multiple arrays that will take will take the new size and will take the older values and ask the user to enter the new remaining ones.
void fVerifRef(int ref[],int ref2[], int n, int pos)
{
int j,val;
val=ref2[pos];
j=fRecherche2(ref,n,val);
while(j!=-1)
{
printf("Reference deja presente.\n");
printf("Veuillez réessayer: ");
scanf("%d",& ref2[pos]);
val=ref2[pos];
j=fRecherche2(ref,n,val);
if(j==-1)
break;
}
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,nb,prods,code;
printf("Combien de produits voulez vous ajouter:");
scanf("%d",& prods);
fVerifVal(&prods);
n=NbArticle();
nb=n+prods;
int ref2[nb],qt2[nb],sds2[nb];
float prix2[nb];
for(i=0;i<n;i++)
{
ref2[i]=ref[i];
qt2[i]=qt[i];
prix2[i]=prix[i];
sds2[i]=sds[i];
}
for (i=n; i<nb; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref2[i]);
fVerifRef(ref,ref2,n,i);
/*fVerif(ref2,i);*/
printf("quantité %d : ", i);
scanf("%d", &qt2[i]);
fVerif(qt2,i);
printf("Prix %d : ", i);
scanf("%f", &prix2[i]);
fVerifReal(prix2,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds2[i]);
fVerif(sds2,i);
}
fEnregNombre(nb);
code=fEnreg(ref2,qt2,prix2,sds2,nb);
if(code==-1)
return -1;
}
int idade, salario,maior, menor, media, somasalario =0, i=0;
char sexo;
char estadoc;
do {
printf("Insira a sua idade:");
scanf("%d", &idade);
if (idade > maior) {
maior = idade;
}
if (idade < menor) {
menor = idade;
}
printf("Insira o seu salario:");
scanf("%d", &salario);
somasalario += salario;
printf("Introduza o seu sexo:");
scanf("%c", &sexo);
printf("Introduza o seu estado civil:");
scanf("%c", &estadoc);
printf("Salario menor que 0!");
}while(idade !=-1);
printf("idade maior: %d", maior);
}
it's my code, and when i run the program, the printf stay like this:
"Insira o seu salario:500
Introduza o seu sexo:Introduza o seu estado civil:
"
someone can help me please?
I have annotated various corrections to your program. It now works, although it does not seem to do anything very useful. In fact it always tells me "Salario menor que 0!"
#include <stdio.h>
#include <limits.h> // added header
int main(void)
{
int idade=0, salario=0, maior=INT_MIN, menor=INT_MAX, somasalario=0;
char sexo=' ', estadoc=' '; // initialised variables
do {
printf("Insira a sua idade: ");
if (scanf("%d", &idade) != 1)
return 1; // input error
if (idade > maior) {
maior = idade;
}
if (idade < menor) {
menor = idade;
}
printf("Insira o seu salario: ");
if (scanf("%d", &salario) != 1)
return 1; // input error
somasalario += salario;
printf("Introduza o seu sexo: ");
if (scanf(" %c", &sexo) != 1) // added space to clean input
return 1; // input error
printf("Introduza o seu estado civil: ");
if (scanf(" %c", &estadoc) != 1) // added space to clean input
return 1; // input error
printf("Salario menor que 0!\n"); // added newline
} while(idade !=-1);
printf("idade maior: %d\n", maior); // added newline
return 0;
}
First at all english its not my first language i will try my best.
Hello guys, I have a problem i'm trying to delete a determinate position of the struct, so instead of deleting the info inside by modifying the string with strcpy or just setting the int or float to 0 i want to erase the data in the struct by changing the position with the next one so 1.2.3.4.5 will be 1.2<-3.4.5 and stay this way 1.2.3.4, problem is after 1h trying to make it works there are some problems, first: if there's only one student after the program ask me for the id to erase, the new id seems to be a random number or like garbage data, so i guess the position changed but the data inside of this id persist.
Example:
id: 1
name: john
lastname: smith
score1: 2
score2: 5
score3: 6
After the function ask me for the id to be erased:
id: 425262
name: john
lastname: smith
score1: 2
score2: 5
score3: 6
the second issue is, if i insert some students, and the program ask for the id to be erased, all id numbers changes to that id i just insert instead of deleting the id target.
Heres the full code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct alumnos{
int id;
char alumno[10];
char apellido[15];
float nota1;
float nota2;
float nota3;
};
int insertar_notas(struct alumnos notas[20],int n,int *id_alumno);
void mostrar_notas(struct alumnos notas[20],int n);
void buscar_alumno(struct alumnos notas[20],int n);
void cambiar_notas(struct alumnos notas[20],int n);
void eliminar_alumno(struct alumnos notas[20],int n);
int main (void){
int menu = 0, n = 0, id_alumno = 1;
struct alumnos notas[20];
puts("\n<><><>Bienvenido al recuento de notas de la escuela<><><>\n");
puts("\nQue deseas hacer?\n");
while (menu != 6){
puts("\n1)Insertas las notas de un alumno\n2)Ver todas las notas\n3)Ver las notas de un alumno\n4)Modificar notas\n5)Eliminar datos del alumno\n6)Salir\n");
scanf("%d", &menu);
switch(menu){
case 1:
n=insertar_notas(notas,n,&id_alumno);
break;
case 2:
mostrar_notas(notas,n);
break;
case 3:
buscar_alumno(notas,n);
break;
case 4:
cambiar_notas(notas,n);
break;
case 5:
eliminar_alumno(notas,n);
break;
}
}
}
int insertar_notas(struct alumnos notas[20], int n,int *id_alumno){
char resp[3];
system("cls");
puts("\n \a Insercion del alumno\n");
while (!strstr(resp,"no")){
fflush(stdin);
printf("\nEl ID de este alumno sera: %d\n", *id_alumno);
notas[n].id=*id_alumno;
(*id_alumno)++;
puts("\nDime el nombre del Alumno\n");
scanf("%10s", notas[n].alumno );
system("cls");
fflush(stdin);
puts("\nDime el apellido del Alumno\n");
scanf("%10s", notas[n].apellido );
system("cls");
puts("\nDime la Primera nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota1 );
system("cls");
puts("\nDime la Segunda nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota2 );
system("cls");
puts("\nDime la Tercera nota trimestral del Alumno[1.23]\n");
scanf("%f", ¬as[n].nota3 );
n++;
system("cls");
puts("\nQuieres volver a insertar otro?[si|no]\n");
scanf("%3s", resp);
strlwr(resp);
}
return n;
}
void mostrar_notas(struct alumnos notas[20],int n){
int i;
system("cls");
if (n != 0 ){
puts("\nLos alumnos insertados son:\n");
for (i = 0; i < n; i++)
{
printf("\n\nID %d\n\n Nombre:%s\n Apellido: %s\n Primera nota:%0.2f\n Segunda nota:%0.2f\n Tercera nota:%0.2f\n\n", notas[i].id, notas[i].alumno, notas[i].apellido ,notas[i].nota1 ,notas[i].nota2 ,notas[i].nota3 );
}
}
else
{
puts("\n \aNo hay registro\n");
}
}
void buscar_alumno(struct alumnos notas[20],int n){
int num = 0;
float media;
if (n != 0){
char ape_alumno[15];
system("cls");
puts("\n\aBusqueda por alumno\n");
puts("\nDime el apellido del alumno\n");
scanf("%15s", ape_alumno);
for ( num = 0; num < n ; num++){
if (strcmp(notas[num].apellido,ape_alumno)==0){
printf("\nEl alumno introducido es: %s %s\n", notas[num].alumno, notas[num].apellido );
media=(notas[num].nota1+notas[num].nota2+notas[num].nota3)/3;
printf("\nLa nota media es %0.2f \n", media);
if (media<5){
puts("\nSuspendido no hace media\n");
}
if (media=5 & media>6){
puts("\nSuficiente\n");
}
}
}
}else{
puts("\a\nRegistro vacio\n");
}
}
void cambiar_notas(struct alumnos notas[20],int n){
char ape_notas[15];
float nueva_nota1,nueva_nota2,nueva_nota3,nota_n1t,nota_n2t,nota_n3t;
int j = 0, submenu_mod = 0, nota_mod;
if (n != 0){
system("cls");
puts("\n \aDime el apellido del alumno a modificar las notas\n");
scanf("%15s", ape_notas);
for (j = 0;j < n; j++){
if (strcmp(notas[j].apellido,ape_notas)==0){
printf("\nLas notas de este alumno %s %s son:\n \n1r Trimestre:%0.2f\n \n2n Trimestre:%0.2f\n \n3r Trimestre:%0.2f\n", notas[j].alumno,notas[j].apellido,notas[j].nota1 ,notas[j].nota2 ,notas[j].nota3 );
while(submenu_mod != 3){
puts("\nQue quieres hacer?:\n\n1)Modificar todas las notas\n2)Modificar solo una nota\n3)Salir\n");
scanf("%d", &submenu_mod);
switch(submenu_mod){
case 1:
puts("\nDime la primera nota trimestral\n");
scanf("%f", &nueva_nota1);
puts("\nDime la segunda nota trimestral\n");
scanf("%f", &nueva_nota2);
puts("\nDime la tercera nota trimestral\n");
scanf("%f", &nueva_nota3);
notas[j].nota1=nueva_nota1;
notas[j].nota2=nueva_nota2;
notas[j].nota3=nueva_nota3;
printf("\nLas nuevas notas de este alumno son:\n \n1r Trimestre:%0.2f\n \n2n Trimestre:%0.2f\n \n3r Trimestre:%0.2f\n", notas[j].nota1 ,notas[j].nota2 ,notas[j].nota3 );
system("pause");
break;
case 2:
while (nota_mod != 4){
puts("\nQue nota trimestral quieres modificar?:\n");
printf("\n1)Nota trimestral %0.2f\n2)Nota trimestral %0.2f\n3)Nota trimestral %0.2f\n4)Salir", notas[j].nota1,notas[j].nota2,notas[j].nota3);
scanf("%d", ¬a_mod);
switch(nota_mod){
case 1:
puts("\nDime la nueva nota del Primer trimestre:\n");
scanf("%f", ¬a_n1t);
notas[j].nota1=nota_n1t;
printf("La nueva nota del primer trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota1);
break;
case 2:
puts("\nDime la nueva nota del Segundo trimestre:\n");
scanf("%f", ¬a_n2t);
notas[j].nota2=nota_n2t;
printf("La nueva nota del Segundo trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota2);
break;
case 3:
puts("\nDime la nueva nota del Tercer trimestre:\n");
scanf("%f", ¬a_n3t);
notas[j].nota3=nota_n3t;
printf("La nueva nota del Tercer trimestre para el alumno %s %s es: \n%0.2f", notas[j].alumno,notas[j].apellido,notas[j].nota3);
break;
}
break;
}
}
}
} else {
puts("\nNo se ha encontrado ese apellido\n");
}
}
} else {
system("cls");
puts("\n \aRegistro vacio\n");
}
}
The function:
void eliminar_alumno(struct alumnos notas[20],int n){
int id_eli = 0, r = 0;
mostrar_notas(notas,n);
puts("\nInserta la id del alumno a eliminar\n");
scanf("%d",&id_eli);
for(r = 0;r < n;r++){
if (notas[r].id = id_eli){
notas[r].id=notas[r+1].id;
n--;
}
}
}
Compile with warnings:
if (notas[r].id = id_eli){
should be
if (notas[r].id == id_eli){
Also, this is wrong:
if (media=5 & media>6){
Suficiente = [5 - 6) right? Then you want if (media >= 5 && media < 6)
Try the following changes in your eliminar_alumno function-
for(r = 0;r < n;r++){
if (notas[r].id == id_eli){
for(i=r;i < (n-1);i++)
notas[i]=notas[i+1];
notas[i].id -= 1;
n--;
}
}