I am System Analyst & Developer student, I'm trying to write code but I'm stuck, structs and fuctions are easy to understand but working with both together... is a... crap...
What an I doing wrong?
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct mercearia
{
char mercadoria[20];
int quantidade;
int valor;
} mercearia;
void EstruturaCadastro(struct mercearia *m)
{
int i;
for(i = 0; i < 5; i++)
{
printf("\n");
setbuf(NULL, stdin);
printf("Insira nome do produto a cadastrar: ");
scanf("%s", &(*m)[i].mercadoria);
setbuf(NULL, stdin);
printf("Insira a quantidade do produto: ");
scanf("%i", &(*m)[i].quantidade);
setbuf(NULL, stdin);
printf("Insira o valor do produto: R$ ");
scanf("%i", &(*m)[i].valor);
}
}
int main(void)
{
setlocale(LC_ALL, "");
struct mercearia m[5];
EstruturaCadastro(&m);
}
It gives me huge error list. Then I wrote same code but without creating array of struct and the code worked perfectly. I am missing up something.
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct mercearia
{
char mercadoria[20];
int quantidade;
int valor;
} mercearia;
void EstruturaCadastro(struct mercearia *x)
{
printf("\n");
printf("Insira nome do produto: ");
scanf("%s", &(*x).mercadoria);setbuf(NULL, stdin);
printf("Insira a quantidade do produto: ");
scanf("%i", &(*x).quantidade);setbuf(NULL, stdin);
printf("Insira o valor do produto: R$ ");
scanf("%i", &(*x).valor);setbuf(NULL, stdin);
}
int main(void)
{
setlocale(LC_ALL, "");
struct mercearia produto;
EstruturaCadastro(&produto);
}
You need to understand the 2nd example (simple) before trying the 1st (harder)
void EstruturaCadastro(struct mercearia *x)
{
printf("\n");
printf("Insira nome do produto: ");
scanf("%s", x->mercadoria);
printf("Insira a quantidade do produto: ");
scanf("%i", &x->quantidade);
printf("Insira o valor do produto: R$ ");
scanf("%i", &x->valor);
}
No need for the setbuf() call, you flush stdin when you press the key
Once you've done this, you can change to m[i]->mercadoria, etc in your first example.
There are all kinds of wrong with your original function. You're passing it a pointer to struct mercearia which is fine for passing in your array. Inside the function you can treat m the same way you would an array, so for example m[0].valor is how you'd access the valor value for the first element.
This means that your various calls to scanf become
scanf("%s", m[i].mercadoria);
scanf("%i", &m[i].quantidade);
scanf("%i", &m[i].valor);
Note, that for reading in a string unlike other data types, you don't need to pass in the pointer to the string so you don't need the preceeding &.
Related
Im doing this struct to print the register of some people i want to register, saving in a array and printing but when i used float it was printing a memory dump and now the int numbers are becoming memory dump too
#include <stdio.h>
typedef struct{
int id_insc[20];
char nome[50];
char altura[10];
int peso[8];
char naturalidade[15];
char estado[10];
} Empregado;
main(){
Empregado empregado[3];
int i;
for(i=0;i<3;i++){
printf("1. Digite o ID da inscricao\n");
scanf("%d", empregado[i].id_insc);
printf("2. Digite o nome do candidato(a)\n");
scanf("%s", empregado[i].nome);
printf("3. Digite a altura\n");
scanf("%s", empregado[i].altura);
printf("4. Digite o peso do candidato (sem casas decimais)\n");
scanf("%d", empregado[i].peso);
printf("5. Digite a naturalidade do candidato(a)\n");
scanf("%s", empregado[i].naturalidade);
printf("6. Digite o estado do candidato(a)\n");
scanf("%s", empregado[i].estado);
system("cls");
}
system("cls");
for(i=0;i<3;i++){
printf(" Id: %d\n Nome: %s\n Altura: %s\n Peso: %d\n Naturalidade: %s\n Estado: %s\n",
empregado[i].id_insc,
empregado[i].nome,
empregado[i].altura,
empregado[i].peso,
empregado[i].naturalidade,
empregado[i].estado);
printf("\n");
}
}
Id: 6487160
Nome: gustavo
Altura: 180
Peso: 6487300
Naturalidade: brasileiro
Estado: parana
the output is printing like this and i typed 11 and 60
For starters in this calls of scanf
printf("1. Digite o ID da inscricao\n");
scanf("%d", empregado[i].id_insc);
printf("4. Digite o peso do candidato (sem casas decimais)\n");
scanf("%d", empregado[i].peso);
you entered only the first elements of the data member arrays
int id_insc[20];
and
int peso[8];
That is these calls of scanf
scanf("%d", empregado[i].id_insc);
and
scanf("%d", empregado[i].peso);
are equivalent to
scanf("%d", &empregado[i].id_insc[0]);
and
scanf("%d", &empregado[i].peso[0] );
because arrays used in expressions with rare exceptions are converted to pointers to their first elements. You can not to enter all elements of an integer array using only one format string "%d".
If you want to enter values for all elements of the arrays you need to use one more for loop.
To output them in the call of printf you have to specify these arguments
empregado[i].id_insc[0],
and
empregado[i].peso[0],
instead of
empregado[i].id_insc,
and
empregado[i].peso,
Again you can not use one conversion specifier %d to output all elements of an integer array. You need to use additional loops. The conversion specifier %d used in a call of printf expects a scalar object of the type int.
I want to make a sort of food ordering system, but whenever I try to make the ID increment by 1 every loop, it doesn't work. It just shows the number 6684076, no matter what.
Here's the code:
struct res {
char nome[40];
char endereco[100];
char pedido[200];
char valor[20];
};
int main() {
char M[100];
int c;
int menu;
int cod = 0;
while (cod < 100) {
cod = cod + 1;
struct res R1, R2, R3, R4;
printf("Digite seu nome: \n");
gets(R1.nome);
fflush(stdin);
printf("Digite seu endereco: \n");
gets(R2.endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
gets(R3.pedido);
fflush(stdin);
printf("Digite o valor total que vai pagar: \n");
gets(R4.valor);
fflush(stdin);
system("cls");
c = c + 1;
printf("Codigo: %d\n", &c);
printf("Nome: %s\n", R1.nome);
printf("Endereco: %s\n", R2.endereco);
printf("Pedido: %s\n", R3.pedido);
printf("Valor: %s\n", R4.valor);
}
return 0;
}
you should've initialised int c to 0 otherwise it'll take a garbage value
I don't see any errors in my compiler and when I debug it, there's no issue with the value of c, so I changed the
printf("Codigo: %d\n", &c);
statment with
printf("Codigo: %d\n", c);
and the output has no issues:
Codigo: 1
Nome: ab
Endereco: cd
Pedido: ef
Valor: gh
Digite seu nome:
EDIT: Additionally you need to initialise c with a meaningful value, e.g. 0, otherwise it might contain a garbage value and reading it provokes undefined behaviour:
int c = 0;
This question already has an answer here:
C - Read special characters like 'ã' using scanf
(1 answer)
Closed 7 months ago.
I'm building a system and i need a char inside a struct to receive a name and 2 values, but when I see the result, the name is always broken from a special character.
#define NOMINMAX
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
float preco;
int quant;
char* prod[50];
} info;
void imprime(info j)
{
printf("|| Produto: %s || preço: %.2f || quantidade: %d ||\n", j.prod, j.preco, j.quant);
}
int main()
{
SetConsoleCP(CP_UTF8);
SetConsoleOutputCP(CP_UTF8);
system("color 0F");
info lojas[50];
for (int x = 0; x < 1; x++)
{
printf("Digite o nome do produto: ");
scanf(" %[^\n]s", &lojas[x].prod);
printf("\nDigite o preço do produto: ");
scanf(" %f", &lojas[x].preco);
printf("\nDigite a quantidade desejada do produto: ");
scanf(" %d", &lojas[x].quant);
system("cls");
}
for (int x = 0; x < 1; x++)
{
imprime(lojas[x]);
}
}
imput:
Digite o nome do produto: Açucar
Digite o preço do produto: 1
Digite a quantidade desejada do produto: 1
expected output:
|| Produto: Açucar || preço: 1.00 || quantidade: 1 ||
result received
|| Produto: A || preço: 1.00 || quantidade: 1 ||
I think the problem may be in these lines:
SetConsoleCP(CP_UTF8);
SetConsoleOutputCP(CP_UTF8);
without them the code works, but the special characters inside printf stop working.
I already tried to use the <locale.h> library but for reasons I don't know it doesn't work in my compiler
I use the embarcadeiro dev-c++
Hi, that's because in C, you should scan a string with another function like gets().
For that IDK if you have to add the library <strings.h> but an example is:
int main () {
char str[50];
printf("Inster a string: ");
gets(str);
printf("The string is: %s",str);
return(0);
}
I recommend you to add the library <string.h> because its easier to make more functions.
See you :)
When I compile the program it seems to work normally but, when it asks for the "cuadrados", the program just stops:
int main(){
int *ptrs, suma=0, n, i, m;
printf("cuantos numeros al cuadrado quiere?: ");
scanf("%i", &n);
int numero[n], cubo[n];
*ptrs=numero
Here is when the program stops:
for(i=0;i<n;i++){
printf("escriba los cuadrados: ");
scanf("%i", numero[i]);
}
printf("Cuantos numero al cubo quiere?: ");
scanf("%i", m);
for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", cubo[i]);
}
I had this issue before but I can't understand why it does not keep running; it just asks for 1 number and then stops with no error or warning.
for(i=0;i<n;i++){
printf("escriba los cuadrados: ");
scanf("%i", &numero[i]);
}
printf("Cuantos numero al cubo quiere?: ");
scanf("%i", &m);
for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", &cubo[i]);
}
You need to give address of the variable in scanf using & operator
This will crash because scanf needs a pointer-to-int, not an int:
scanf("%i", numero[i]);
This will not:
if (scanf("%i", &numero[i]) == 1) {
/* do something */
}
else {
/* scanf failed */
}
Note that not testing the scanf return value is always asking for trouble. As is not using your compiler's maximum warning level and turning all warnings into errors.
Im doing a struct to register students´ info, previously I asked the user how many he wanted to register and proceeded to do it with a for loop:
case 1:
printf("How many students you want to register?:(no more than 10) \n");
scanf("%d", &num);
fflush(stdin);
printf("\n");
for(int i=0;i<num;i++){
alumno[i]=llenarInfo(alumno[i]);
}
printf("---------------------\n");
but how can I do it 1 at a time? I tried increasing i after the loop for but if I register 2 or more and want to print them all it only prints the last one and when asking for the name of the student (atm of filling the info) it automatically jumps to the next member of the struct:
struct Usuario llenarInfo(struct Usuario alumno){
printf("Dame el nombre: ");
gets(alumno.nombre);
fflush(stdin);
printf("");
jumps this^^
printf("Dame el codigo de alumno: ");
scanf("%d", alumno.codigo);
fflush(stdin);
printf("");
printf("Dame el email: ");
scanf("%s", alumno.email);
fflush(stdin);
printf("");
printf("Que carrera estudia?: ");
scanf("%s", alumno.carrera);
fflush(stdin);
printf("");
printf("Cual es el sexo? H Hombre- M Mujer: ");
scanf("%s", alumno.sexo);
fflush(stdin);
printf("");
printf("Cual es la edad?: ");
scanf("%s", alumno.edad);
fflush(stdin);
printf("\n");
return alumno;
but how can i do it 1 at a time?
from your question I think the fflush is not working
you can define a simple flush function to use it instead
void _flush() {
int c;
while((c = fgetc(stdin)) != EOF) {
if(c == '\n') break;
}
}
besides you should use fgets instead of gets, because gets doesn't check for overflows and that makes it dangerous, and it's no more in C standard!