int realizar_reparaciones(int naves_a_reparar, int repuestos_laser, int repuestos_escudos, int repuestos_compensadores){
int caracter_valido = 0;
char reparacion_necesaria;
int naves_con_alambre = 0;
int contador_laser = 0;
int contador_escudo = 0;
printf ("A continuación deberá ingresar uno de los siguientes valores por nave: L (Generador Láser) o E (Generador de escudo deflector)\n");
for (int i = 1; i <= naves_a_reparar; i = i + 1){
while (caracter_valido == 0){
printf ("Ingrese la reparación que hay que realizarle a la nave %d: ", i);
scanf (" %c", &reparacion_necesaria);
switch (reparacion_necesaria){
case 'L':
if (repuestos_laser == 0){
naves_con_alambre = naves_con_alambre + 1;
} else {
repuestos_laser = repuestos_laser - 1;
contador_laser = contador_laser + 1;
}
caracter_valido = 1;
break;
case 'E':
if (repuestos_escudos == 0){
naves_con_alambre = naves_con_alambre + 1;
} else {
repuestos_escudos = repuestos_escudos - 1;
contador_escudo = contador_escudo + 1;
}
caracter_valido = 1;
break;
default:
printf ("Ingrese unicamente alguno de los caracteres previamente mencionados\n");
break;
}
}
}
printf ("Se utilizaron %d generadores láser\n", contador_laser);
printf ("Se utilizaron %d generadores de escudos deflectores\n", contador_escudo);
printf ("Se utilizaron %d compensadores de aceleracion\n", contador_compensador);
return naves_con_alambre;
I have this function in C. i can only get the FOR to run once even if "naves_a_reparar" is 30 or any high number. After that, it goes out of the FOR loop and function ends. Why is this happening?
Related
To solve my problem I need to get out of the while loop if the str2 is empty.
while (elementos <= tamanho - jogada || str2 == NULL);
This is the code:
#include <stdio.h>
#include <string.h>
#define BUFFER 100
unsigned int randaux() {
static long seed = 1;
return (((seed = seed * 214013L + 2531011L) >> 16) & 0x7fff);
}
/* Implementação do procedimento MostraLamberta */
unsigned int MostraLamberta(int *tabuleiro, int tamanho) {
int i, casa, elementos;
int jogada = 0;
char novostr[BUFFER], str2[BUFFER]; /* novo vetor para receber os char */
do {
scanf("%d %d", &casa, &elementos);
for (i = 0; i < tamanho; i++) { /*Loop para percorrer o int tabuleiro um a um */
if (tabuleiro[i] == 0) { /*Comparar se for 0 vai para o vetor como O */
novostr[i] = 'O';
} else { /* Se não vai para o vetor como X */
novostr[i] = 'X';
}
}
if (tamanho >= 10) {
novostr[i] = '\0';
for (i = 1; i < tamanho; i++) {
if (i == 10) {
printf("%d", (i) / 10);
} else {
printf(" ");
}
}
printf("\n");
for (i = 1; i < tamanho + 1; i++) {
if (i >= 10) {
printf("%d", i % 10);
} else {
printf("%d", i);
}
printf;
}
} else {
for (i = 0; i < tamanho; i++) {
if (i == 10) {
printf("%d", i % 10);
} else {
printf("%d", i + 1);
}
}
}
printf("\n");
novostr[i] = '\0'; /*Termina a string */
jogada++;
printf("%s", novostr);
printf("\nJogada [%d]: %d %d", jogada, casa, elementos); /*Imprime nova string */
for (i = casa - 1; i < elementos + casa - 1; i++) {
if (tabuleiro[i] == 0) { /*Comparar se for 0 vai para o vetor como O */
novostr[i] = 'X';
tabuleiro[i] = 1;
continue;
} else { /* Se não vai para o vetor como X */
novostr[i] = 'O';
tabuleiro[i] = 0;
str2[i] = tabuleiro[i];
}
novostr[i] = '\0';
printf("%d", str2[i]);//in here if its empty, the loop is over
}
printf("\n");
} while (elementos <= tamanho - jogada || str2 == NULL);
if (jogada % 2 == 0) {
printf("Jogada inválida, perde jogador 2.");
} else {
printf("Jogada inválida, perde jogador 1.");
}
}
void main() {
int i, num, saltos, tamanho, tabuleiro[BUFFER]; /*Implementa as variáveis inteiras */
scanf("%d %d", &tamanho, &saltos);
// saltar os primeiros números aleatórios, para ter sequências distintas
for (i = 0; i < saltos; i++) /*Loop */
randaux(); /*Chama a funcão randaux */
/* Chamar o procedimento para gerar um novo tabuleiro */
for (i = 0; i < tamanho; i++) {
num = randaux(); /*Grava um numero aleatório numa nova variável */
if (num % 2 == 0) { /*VC* se o numero aleatório C) par ou impar */
tabuleiro[i] = 0;
} else {
tabuleiro[i] = 1;
}
}
MostraLamberta(tabuleiro, tamanho); /*Chama a função e passa dois argumentos) */
}
[]
[]
It is unclear what your code does, but there are some problems:
the do / while loop is an error prone construction. It is less confusing to use a for (;;) (aka for ever) loop and make explicit tests to break from it, such as if (scanf("%d %d", &casa, &elementos) != 2) break;
the second part of the test while (elementos <= tamanho - jogada || str2 == NULL); is moot: str2 is an array, it cannot be NULL. If you want to test for an empty string, use str2[0] == '\0' instead.
str2 is not properly constructed: the only place where it gets modified is: str2[i] = tabuleiro[i]; but tabuleiro[i] is set to 0 just before this statement, so part of str2 is uninitialized and the only elements that get modified are null bytes.
In the OP code, the following lines get into infinite loop.
while (elementos <= tamanho - jogada || str2 == NULL);
Few potential issues to look at:
The 'str2' expression is always NON-null. Recall that in "C", the value of an array is the address of the first element. If you want to test is a string is "empty" consider strlen(str2) == 0, or similar.
For any case that str2 is "not empty", the while will go into infinite loop if elementos <= tamanho - jogada. Usually, you will see modification to one of the variables in the condition inside the loop body. e.g. jopada++
I have to make a program that reads an integer (N+) and then read a series of other integers (N+), but the program needs to check if the user has inputted chars mixed in the numbers the scanf() reads, in affirmative, the program will repeat the scanf(). So I decided to check the return value of scanf(). It works if I use only character input, but when I mixed it with integers, the program reads the integer and uses the maintained character on the buffer. How can I solve this?
#include <stdio.h>
int main() {
int tamanho = 0, verificador = 0;
do {
printf("Digite um valor n>0: ");
verificador = scanf("%d", &tamanho);
getchar();
if (verificador != 1) {
printf("\nO programa aceita apenas valores inteiros\n");
printf("Tente novamente\n");
}
} while (verificador != 1);
int conjunto[tamanho];
do {
printf("Digite os numeros do conjunto de tamanho 'n': ");
for (int i = 0; i < tamanho; i++) {
verificador = scanf("%d", &conjunto[i]);
if (verificador != 1) {
printf("\nO programa aceita apenas números\n");
printf("Tente novamente\n");
getchar();
break;
}
}
} while (verificador != 1);
printf("numero = %d\n", tamanho);
for (int i = 0; i < tamanho; i++) {
if (i <= tamanho - 2) {
printf("%d, ", conjunto[i]);
} else if (i == tamanho - 1) {
printf("%d.\n", conjunto[i]);
}
}
return 0;
}
I can't get out of this:
In the following code, if I choose option 1, I let the code begin asking the input described on 1/* InserimentoNaviP1 */; but when the program runs, without error in compiling, the function main() avoids it; the first printf is
("P1: inserisci la riga dove fare fuoco: ");
Can you please help me?
Below a part of the code (I cannot insert it all)
main() {
scanf("%d", &a);
switch (a) {
case 1:
printf("Che vinca il migliore!! \n");
break;
return 0; // Unreachable code...
}
Sleep(1000);
InizializzaGrigliaP1();
InizializzaGrigliaP2();
/* InserimentoNaviP1 */
for (r = 0; r < righe; r++) {
for (c = 0; c < colonne; c++) {
printf("Inserisci riga %d e colonna %d: ", r, c);
scanf("%d", &grigliaP1[r][c]);
}
if (grigliaP1[r][c] == 1) {
printf("nave inserita!\n");
contnum_naviP1++;
printf("restano da inserire %d navi!\n", P1_num_navi - contnum_naviP1);
}
}
for (t = 0;; t++) {
//SparaP1
{
printf("P1: inserisci la riga dove fare fuoco: ");
system("pause");
}
} // added
} // added
#include <stdio.h>
#include <stdlib.h>
struct Eleve {
float note;
};
void saisirNote(struct Eleve E, FILE* fichedeNote, float T[30]) {
char rep;
fichedeNote = fopen("C:/Users/Ayoub/Desktop/TDTP/EX2/Notef/Fnote.dat", "wb");
int i = 0;
int en_desordre = 1;
float tmp = 0.0;
do {
printf("\nSaisir Un Note %d: ", (i + 1));
scanf("%f", &E.note);
T[i] = E.note;
i++;
fwrite(&E, sizeof(&E), 1, fichedeNote);
if (fwrite != 0)
printf("\n\nSaisie de note avec Succes ! \n\n");
printf("\n\nVoulez-Vous Saisir Un autre Note ?: ");
scanf(" %c", &rep);
} while (rep != 'N');
for (int j = 0; j<i; j++) {
printf("Note %d: %.2f\n", (j + 1), T[j]);
}
while (en_desordre == 1) {
en_desordre = 0;
for (int j = 0; j<i; j++) {
if (T[j]>T[j + 1]) {
tmp = T[j + 1];
T[j + 1] = T[j];
T[j] = tmp;
en_desordre = 1;
}
}
}
while (fread(&E, sizeof(&E), 1, fichedeNote)) {
for (int j = 0; j<i; j++) {
E.note = T[j];
fwrite(&E, sizeof(&E), 1, fichedeNote);
}
}
printf("\n\n***Note Trie***\n\n");
while (fread(&E, sizeof(&E), 1, fichedeNote)) {
printf("\nNote = %f\n\n", E.note);
}
}
int main()
{
float T[30];
FILE* fichedeNote;
struct Eleve E;
saisirNote(E, fichedeNote, T);
}
So basically the program is about to read Marks from the file and put it in a table then sore it , keep in mind it's (Binary File) , it looks i got an issue in Editing the record in the file but didn't figured out how to do it , hope you guys figure it out.
More than the remarks already did like about sizeof(&E) :
In the line
T[i] = E.note;
you can write out of T, because you never check i < 30. For that better to give the size of T (30) rather than to give fichedeNote and E non initialized in argument.
In the line
if (T[j]>T[j + 1]) {
you access to the non initialized entry T[j + 1] when j is i-1, or may be out of T is
You read/write the memory representation of Eleve in your file, with the associated little/big endian problem
It seems logic to read the file to put the notes in T before to get new notes
A proposal :
#include <stdio.h>
#include <stdlib.h>
struct Eleve {
float note;
};
size_t lireNotes(float T[], size_t max, const char * fn)
{
FILE* fichedeNote = fopen(fn, "rb");
size_t sz = 0;
struct Eleve E;
if (fichedeNote == NULL)
return 0;
while ((sz != max) && fread(&E, sizeof(E), 1, fichedeNote))
T[sz++] = E.note;
fclose(fichedeNote);
/* debug */
puts("anciennes notes:");
for (size_t j = 0; j<sz; j++) {
printf("Note %d: %.2f\n", (j + 1), T[j]);
}
putchar('\n');
return sz;
}
void saisirNote(float T[], size_t max, size_t sz, const char * fn) {
char rep;
FILE* fichedeNote = fopen(fn, "wb");
if (fichedeNote == NULL) {
printf("impossible d'ouvrir %s en ecriture\n", fn);
return;
}
do {
struct Eleve E;
if (sz == max) {
puts("plus de place pour une nouvelle note");
break;
}
printf("\nSaisir Une Note %d: ", (sz + 1));
if (scanf("%f", &E.note) != 1)
puts("note invalide");
else {
T[sz++] = E.note;
puts("Saisie de note avec Succes !");
}
printf("Voulez-Vous Saisir Une autre Note ?: ");
if (scanf(" %c", &rep) != 1)
break;
} while (rep != 'N');
/* debug */
puts("\nliste des notes:");
for (size_t j = 0; j<sz; j++) {
printf("Note %d: %.2f\n", (j + 1), T[j]);
}
/* tri */
if (sz > 1) {
int en_desordre;
do {
en_desordre = 0;
for (size_t j = 0; j < (sz-1); j++) {
if (T[j]>T[j + 1]) {
float tmp = T[j + 1];
T[j + 1] = T[j];
T[j] = tmp;
en_desordre = 1;
}
}
} while (en_desordre == 1);
}
/* debug */
puts("\n***Note Trie***:");
for (size_t j = 0; j<sz; j++) {
printf("Note %d: %.2f\n", (j + 1), T[j]);
}
/* update file */
for (size_t j = 0; j<sz; j++) {
struct Eleve E;
E.note = T[j];
fwrite(&E, sizeof(E), 1, fichedeNote);
}
fclose(fichedeNote);
}
int main()
{
float T[30];
const char * fn = "/tmp/Fnote.dat";
size_t sz = lireNotes(T, sizeof(T)/sizeof(*T), fn);
saisirNote(T, sizeof(T)/sizeof(*T), sz, fn);
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra e.c
pi#raspberrypi:/tmp $ rm -f Fnote.dat
pi#raspberrypi:/tmp $ ./a.out
Saisir Une Note 1: 11
Saisie de note avec Succes !
Voulez-Vous Saisir Une autre Note ?: o
Saisir Une Note 2: 22
Saisie de note avec Succes !
Voulez-Vous Saisir Une autre Note ?: o
Saisir Une Note 3: 15
Saisie de note avec Succes !
Voulez-Vous Saisir Une autre Note ?: N
liste des notes:
Note 1: 11.00
Note 2: 22.00
Note 3: 15.00
***Note Trie***:
Note 1: 11.00
Note 2: 15.00
Note 3: 22.00
pi#raspberrypi:/tmp $ ./a.out
anciennes notes:
Note 1: 11.00
Note 2: 15.00
Note 3: 22.00
Saisir Une Note 4: 0
Saisie de note avec Succes !
Voulez-Vous Saisir Une autre Note ?: O
Saisir Une Note 5: 44
Saisie de note avec Succes !
Voulez-Vous Saisir Une autre Note ?: N
liste des notes:
Note 1: 11.00
Note 2: 15.00
Note 3: 22.00
Note 4: 0.00
Note 5: 44.00
***Note Trie***:
Note 1: 0.00
Note 2: 11.00
Note 3: 15.00
Note 4: 22.00
Note 5: 44.00
pi#raspberrypi:/tmp $
Note I still use the struct Eleve, probably the goal is to add other fields like the name etc
P.S. sorry for non French people, I added messages in French ;-)
I'm a beginner in C, I'm trying to read a file in order to update a struct but every time I do it it gives me an error (I'm working with visual studio 2013).
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Registro{
int cedula;
char nombre[20];
char apellido[20];
char direccion[50];
int ingreso;
};
void agregarP(struct Registro * informacion, int * n){
int op,i,aux;
printf("Cuantas personas desea agregar?\n");
fflush(stdin);
scanf_s("%i", &op);
aux = op;
op += *n;
for (i = *n; i < op; i++){
printf("Introduzca la cedula\n");
scanf_s("%i", &informacion[i].cedula);
printf("Introduzca el nombre\n");
fflush(stdin);
gets_s(informacion[i].nombre);
printf("Introduzca el apellido\n");
gets_s(informacion[i].apellido);
printf("Introduzca la direccion\n");
gets_s(informacion[i].direccion);
printf("Introduzca el ingrso anual\n");
scanf_s("%i", &informacion[i].ingreso);
system("cls");
}
*n += aux;
}
bool comprobacion(int n1, int n2){
if (n1 == n2){
return true;
}
else {
return false;
}
}
void borrar(struct Registro * s, int *n){
int i, ced;
struct Registro aux;
bool compr;
printf("Introduzca la cedula de la persona que desea borrar\n");
fflush(stdin);
scanf_s("%i",&ced);
for (i = 0; i < *n; i++){
if (s[i].cedula == ced){
compr = comprobacion(*n, i);
if (compr){
break;
}
else{
aux = s[*n - 1];
s[*n - 1] = s[i];
s[i] = aux;
break;
}
}
}
*n -= 1;
}
void mostrar(struct Registro * informacion, int n){
int i;
printf("Cedula \t Nombre \t Apellido \t Direccion \t Ingreso \n");
for (i = 0; i < n; i++){
printf("%i \t ", informacion[i].cedula);
printf("%s \t ", informacion[i].nombre);
printf("%s \t ", informacion[i].apellido);
printf("%s \t ", informacion[i].direccion);
printf("%i \n", informacion[i].ingreso);
}
}
void mostrarPorOrden(struct Registro * s, int n){
int i, j,cont = 0, op;
struct Registro aux;
printf("1 para mostrar por orden de cedula\n");
printf("2 para mostrar por orden de apellido\n");
fflush(stdin);
scanf_s("%i", &op);
switch (op){
case 1: for (i = 0; i < n+1; i++){
cont = 0;
for (int j = 0; j < n - 1; j++)
{
if (s[j].cedula > s[j + 1].cedula){
aux = s[j+1];
s[j + 1] = s[j];
s[j] = aux;
cont++;
}
}
if (cont == 0) break;
}
mostrar(s, n);
break;
case 2: for (i = 0; i < n + 1; i++){
cont = 0;
for (int j = 0; j < n - 1; j++)
{
if (s[j].apellido[0] > s[j + 1].apellido[0]){
aux = s[j+1];
s[j + 1] = s[j];
s[j] = aux;
cont++;
}
}
if (cont == 0) break;
}
mostrar(&s[0], n);
break;
}
}
void guardarArch(FILE * ff, struct Registro * s, int n){
fopen_s(&ff, "Datos.txt", "w");
int i;
for (i = 0; i < n; i++){
fprintf(ff,"%d", s[i].cedula); fprintf(ff, "\n");
fprintf(ff, s[i].nombre); fprintf(ff, "\n");
fprintf(ff, s[i].apellido); fprintf(ff, "\n");
fprintf(ff, s[i].direccion); fprintf(ff, "\n");
fprintf(ff, "%d",s[i].ingreso); fprintf(ff, "\n");
}
fclose(ff);
}
void leerArch(FILE * ff, struct Registro * s, int * n){
fopen_s(&ff, "Datos.txt", "r");
int i = 0;
while (!feof(ff)){
}
fclose(ff);
}
void main(){
FILE * infor = new FILE;
struct Registro informacion[30];
int op = -1;
int persona = 0;
while (op != 0){
printf("1 para agregar una persona\n");
printf("2 para mostrar\n");
printf("3 para borrar\n");
printf("4 para mostrar ordenado\n");
printf("5 para guardarlo en un archivo\n");
printf("6 para leer de un archivo\n");
printf("0 para salir\n");
scanf_s("%i", &op);
fflush(stdin);
switch (op)
{
case 1: agregarP(&informacion[0], &persona);
printf("%i", persona);
break;
case 2: mostrar(&informacion[0], persona);
break;
case 3: borrar(&informacion[0], &persona);
break;
case 4: mostrarPorOrden(&informacion[0], persona);
break;
case 5: guardarArch(infor, &informacion[0], persona);
break;
case 6: leerArch(infor, &informacion[0], &persona);
break;
}
system("pause");
system("cls");
}
}
PD: Sorry for my english.
Edited.
This is the part where I'm having trouble, it breaks automatically. It reads the stuff now but with a lot of new lines
int ayudaLeer(FILE * ff, struct Registro * s, int * n){
if (feof(ff)) return -1;
char * c = new char[];
int p = fgetc(ff);
fscanf_s(ff, "%d", &s[*n].cedula);
fgets(c, 20, ff);
fgets(s[*n].nombre, 20, ff);
fgets(s[*n].apellido, 20, ff);
fgets(s[*n].direccion, 20, ff);
fscanf_s(ff, "%d", &s[*n].ingreso);
*n+=1;
ayudaLeer(ff, s, n);
}
void leerArch(FILE * ff, struct Registro * s, int * n){
fopen_s(&ff, "Datos.txt", "r");
int i = 0;
ayudaLeer(ff, s, &i);
*n = i-1;
fclose(ff);
}