Scanf() don't read number 0 or read is wrong - c

Hello I have a litlle problem. I trying to make a bank wait time program but the time i read a 0 value with scanf() it do not read or read wrong. I did some search but noting that solves my problem.
this is the code.. its in C language.
#include <stdio.h>
int main(){
int c, n, t,i,d;//entradas do usuário (caixas, usuários, momento de chegada, tempo de atendimento
int menor_espera=0;// caixa de menor tempo de espera
int tempo_maximo = 20;// tempo maximo de espera por atencimento
int resultado=0;//Numero de pessoas com mais de 20 minutos de espera por atendimento
scanf(" %u %u %*c\n", &c, &n);// Lê o numero de caixas, numero de clientes no dia
if(c>0 && n>0){//iniciação só com valores positivos e possiveis c>1, n>1 (1 caixa e um cliente)
int caixa[c];// declara o um vetor de caixas
for(i=0;i<n;i++){// Loop de numero de usuários
scanf(" %u %u %*c\n", &t, &d);//Lê um cliente (T e D)
printf("print: %u %u\n", c, n);
int j;
for(j=0; j<c;j++){// loop de caixas
if(caixa[j]<caixa[menor_espera]){//chaca se o caixa atual é o primeiro caixa disponivel (caixa com menos tempo de uso)
menor_espera = j;//positivo, atualiza o caixa de menor espera
}
}if(caixa[menor_espera]-t>tempo_maximo){//checa se o cliente terá de esperar mais que o tempo maximo para ser atendido baseado na sua chegada
resultado++;//positivo, atualiza o contador de usuário que esperaram mais que o tempo maximo
}caixa[menor_espera] += d;// atualiza o tempo de uso do caixa que foi utilizado
}
printf("Resultado final: %d\n", resultado);// exibe resultado final
}getch();
}
and this is a input
1 16
0 10
0 10
0 10
3 10
5 10
7 10
11 10
13 10
14 10
15 10
16 10
17 10
18 3
19 10
20 10
23 3
that's the output i have
print: 10 0
print: 0 0
print: 0 3
print: 0 5
print: 0 7
print: 0 11
print: 0 13
print: 0 14
print: 0 15
print: 0 16
print: 0 17
print: 0 18
print: 19 10
print: 0 10
print: 3 3
print: 3 3
Resultado final: 16
but it shoud'nt look like this.
Tks for any help. if i found the solution i'll post here.

One issue is that you are not capturing or testing the return value from scanf(). It returns the number of items it parsed, or -1 on an i/o error.
Consider something like this to at least find out if this might be a problem:
if (scanf(" %u %u %*c\n", &t, &d) < 2) //Lê um cliente (T e D)
printf ("input conversion or i/o error\n");

This is problematic:
scanf(" %u %u %*c\n", &c, &n);
It looks for two numbers, some white space, and a non-white space character that is ignored, followed by more white space (which may or may not be a newline).
Given your input file, the first scanf() reads:
1 16
0
The next character to be read will be the 1 of the 10 on the second line of data. That's why you have problems.
Use fgets() to read a line at a time, and sscanf() to parse the line. And test the results of both fgets() and sscanf() (or scanf() if you insist on using it).
Here's an approximation to what you need.
#include <stdio.h>
int main(void)
{
int c, n, t,d;
int menor_espera = 0;
int tempo_maximo = 20;
int resultado = 0;
char line[4096];
if (fgets(line, sizeof(line), stdin) != 0)
{
if (sscanf(line, "%u %u", &c, &n) != 2)
return(1);
if (c > 0 && n > 0)
{
int caixa[c]; // VLA - uninitialized
for (int i = 0;i < n; i++)
{
if (fgets(line, sizeof(line), stdin) == 0)
break; // EOF or error
if (scanf(line, "%u %u", &t, &d) != 2)
break; // EOF or error
printf("print: %u %u\n", c, n); // Not t and d??
for (int j = 0; j < c; j++)
{
// Accessing uninitialized data in caixa array!
if (caixa[j] < caixa[menor_espera])
menor_espera = j;
}
if (caixa[menor_espera] - t > tempo_maximo)
resultado++;
caixa[menor_espera] += d;
}
printf("Resultado final: %d\n", resultado);
}
}
return(0);
}
I think there are some logic errors in the original code (some highlighted with comments), but I'm not sure what the corrections should be.

Related

Why appears the wrong number

the code doesn't work and i don't know why but i'm a begginer in this language so the fault could be mine
#include <stdio.h>
int horascomeco(){
int horasco; int minutosco; int totalcomeco;
printf("-----A que horas e minutos começou o recolher?\nHoras:");
scanf("%d", &horasco);
printf("Minutos:");
scanf("%d", &minutosco);
printf("R:O recolher começou ás %d horas e %d minuto\n\n\n", horasco, minutosco);
totalcomeco = horasco*60 + minutosco;
printf("%d\n", totalcomeco);
return totalcomeco;
}
int horasapanhado(){
int horasapa; int minutosapa;int totalapanhado;
printf("-----A que horas e minutos foi apanhado?\nHoras:");
scanf("%d", &horasapa);
printf("Minutos:");
scanf("%d", &minutosapa);
printf("R:Voce foi apanhado ás %d horas e %d minutos\n\n\n", horasapa, minutosapa);
totalapanhado = horasapa*60 + minutosapa;
printf("%d\n", totalapanhado);
return totalapanhado;
}
int tempodemulta(){
int minutosforadalei;
int horascomeco;
printf("%d\n", horascomeco);
int horasapanhado;
printf("%d\n", horasapanhado);
minutosforadalei = horasapanhado - horascomeco;
printf("A sua multa vai ser respetiva a %d minutos fora do recolher obrigatorio", minutosforadalei);
}
int main(){
horascomeco();
horasapanhado();
tempodemulta();
return 0;
}
why appears 14705... ? minutosforadalei should be = 1 in that print
int tempodemulta(){
int minutosforadalei;
int horascomeco;
printf("%d\n", horascomeco); // no value assigned to horascomeco!
int horasapanhado;
printf("%d\n", horasapanhado); // no value assigned to horaspanhado!
minutosforadalei = horasapanhado - horascomeco;
printf("A sua multa vai ser respetiva a %d minutos fora do recolherobrigatorio", minutosforadalei);
}
You are printing and calculating with variables that you have not assigned any value to yet. You have to assign a value to a variable before you try to use that value.

How to create a finished, executable console program from code [duplicate]

This question already has answers here:
How to compile C code in Linux to run on Windows? [duplicate]
(4 answers)
Closed 2 years ago.
I started learning how to program last month (and have been making really slow progress ever since), so I really don't know much about stuff.
I code in a Linux (Ubuntu 20.04) and I use VSCode, Sublime, and Code::Blocks (trying to find the perfect IDE for me). I want to learn how to create an executable Windows file so I can share the program I made with my friends (they're all Windows users). Even though it's a really silly objective, learning how to do that will certainly be really useful in the future. I'll leave the code below so you can see it if you like.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Cute little program that allows the user to choose between calculating factorials, finding the real roots
// of quadratic equations and counting the quantity of even numbers inside the sequence they can tipe.
// I'm a native (Brazilian) Portuguese speaker and therefore the program will communicate with the user through (Brazilian) Portuguese language.
// this function finds real roots of quadratic equations
void findRoots(){
float a, b, c;
printf("Calculadora de raízes de equações do segundo grau. \n Os parâmetros devem ser observados da fórmula: ax² + bx + c\n");
printf("\nInsira o parâmetro 'a':\n");
scanf("%f", &a);
printf("Insira o parâmetro 'b':\n");
scanf("%f", &b);
printf("Insira o parâmetro 'c':\n");
scanf("%f", &c);
float discriminante = pow(b,2) - (4 * a * c);
float sqrtds = sqrt(discriminante);
float x1 = -b - sqrtds;
float x2 = -b + sqrtds;
float den = 2 * a;
if(a == 0){
printf("Essa não é uma equação do segundo grau!\n");
}else {
if (discriminante < 0){
printf("A equação não possui raízes reais\n");
}else if (discriminante == 0) {
float raiz = -b / den;
printf("A única raíz da equação é %f\n", raiz);
} else {
float raiz1 = x1 / den;
float raiz2 = x2 / den;
printf("O discriminante da equação é %f\n", discriminante);
printf("Logo, a equação possui 2 raízes reais. \n Uma delas é %f \n A outra é %f\n", raiz1, raiz2);
}
}
}
//this function calculates factorials
void fatorial(){
int n;
int x = 0;
printf("Calculadora de fatoriais.\n Insira um número até 12: \n");
scanf("%d", &n);
int y = n;
if(n == 0){
printf("0! é 1\n");
}else if ( n < 13 && n > 0){
while ( y > (x + 1) ){
x = x + 1;
n = n * (y - x);
}
printf("%d! é %d\n", y, n);
} else{
printf("O programa não é capaz de calcular esse fatorial.");
}
}
//this function asks the user to enter a sequence and then tells how many even numbers there are in it (it also shows the quantity of odd numbers)
int paridade(){
printf("Digite o tamanho da sequência:\n");
int n;
scanf("%d", &n);
int par = 0;
int impar = 0;
int x = 0;
int y;
while(x < n){
x = x + 1;
printf("Digite o %dº numero inteiro: \n", x);
scanf("%d", &y);
if((y%2) == 0 ){
par = par + 1;
}else {
impar = impar + 1;
}
}
printf("Na sequencia existem %d números pares e %d números ímpares.\n", par, impar);
return 0;
}
// the main functions allows the user to choose between the funcions mentioned above. It also allows the user to finish the program.
int main(){
printf("Bem vindo(a).\n");
int x = 1;
while(x!= 0){
int opcao;
printf("\nEscolha entre:\n -Calcular o fatorial de um número (Insira 1)\n -Calcular raízes de uma equação do segundo grau (Insira 2)\n -Contar a quantidade de números pares ou ímpares em uma sequência (Insira 3)\n -Terminar o programa (Insira 4)\n");
scanf("%d", &opcao);
switch (opcao)
{
case 1:
fatorial(); //calculates factorial
break;
case 2:
findRoots(); //self-explicative
break;
case 3:
paridade();
break;
case 4:
x = 0; /// closes program
break;
default:
printf("Você selecionou uma opção inválida."); // error message (Invalid option)
break;
}
}
printf("Obrigado por usar o programa."); // "thnks for using the program"
return 0;
}
I code in a Linux (Ubuntu 20.04) and I use VSCode, Sublime, and Code::Blocks (trying to find the perfect IDE for me).
The IDE or editor, in general, is orthogonal to the compiler.
I want to learn how to create an executable Windows file so I can share the program I made with my friends (they're all Windows users).
That means you are cross-compiling. That is, targeting a different platform than the one you are running your compiler on. How to do that depends on your compiler, but it is doable in both GCC and Clang.
Having said that, if you have just started, then you may find it a little be complicated. It may require to install extra packages, tweak things or build the compiler. It is usually way easier to setup a VM with Windows and compile (and test!) the program on it.
The same applies in the opposite case: compiling a Linux program under Windows.
Even though it's a really silly objective, learning how to do that will certainly be really useful in the future.
Certainly, but it is not a silly objective at all. Many important projects are cross-compiled every day.

Why does my program enter an infinite loop when I use float values in a While loop?

I was tasked to do a program to read the name of one student, 4 of their subjects and their respective grades. I have worked with for and while loops, also with if statements and here is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main() {
printf("Este programa captura el nombre de un alumno \n");
printf ("y cuatro de sus materias y sus respectivas notas\n");
printf ("Nota: El programa solo toma en cuenta los dos primeros\n");
printf ("decimales de la notas expresada.\n\n");
char alumno[40] = {'\0'};
char mat[4][20] = {'\0', '\0', '\0', '\0'};
float calif[4] = {-1, -1, -1, -1};
int i;
while (alumno[0] == '\0') {
printf("Ingresa el nombre del alumno: ");
gets(alumno);
if (alumno[0] == '\0') {
printf("\nError. El alumno debe de llevar un nombre.");
printf ("\nTrata nuevamente\n\n");
};
};
for (i = 0; i < 4; ++i) {
while (mat[i][0] == '\0') {
printf("Ingresa el nombre de la materia %d: ", i+1);
gets(mat[i]);
if (mat[i][0] == '\0') {
printf("\nError. Las materias deben ser declaradas.");
printf ("\nTrata nuevamente.\n\n");
};
};
while (calif[i] < 0 || calif[i] > 10) {
printf("Ingrese la nota correspondiente a esta materia (0-10): ");
scanf("%2.2f", calif[i]);
if (calif[i] < 0 || calif[i] > 10) {
printf("\nError. Debe ingresar una nota válidad entre 0 y 10.");
printf ("\nTrata nuevamente.\n\n");
};
};
};
return 0;
};
The program seems to be working fine until it gets to the point to ask the grade of the first subject. Any grade I put it causes an infinite loop. I have searched about this problem to no avail. So please, let me know what I am doing wrong here.
There are multiple problems in your code:
[major] you read the mark with scanf("%2.2f", calif[i]): the format string is incorrect, the first 2 means read at most 2 bytes and the .2 is an error as scanf() does not support the precision syntax at all. It should just be "%f" and you should pass the address of the destination variable &calif[i] instead of its value. Furthermore, you should test the return value to check for invalid or missing input.
the prototype for main is int main(), int main(void) or int main(int argc, char *argv[]), the missing return type is an obsolete syntax.
reading input with gets() is risky as there is no way to prevent buffer overflow with sufficiently long input strings. You should instead use scanf("%39s", alumno) or fgets(alumno, sizeof alumno, stdin) and test the return value to detect premature end of input stream. Same remark for the second instance of gets().

Counting characters, words, lines an paragraphs in C

I'm trying to count the characters, words, lines an paragraphs in C from the stdin.
something is not working and I don't know why.
#include <stdio.h>
int main(int argc, char const *argv[])
{
int pCount=0, parCount=0, cCount=0, lCount=0;
double prom=0;
char c;
int newln_cnt=0;
while ((c=getchar())!=EOF){
cCount++;
switch (c)
{
case '\n':
newln_cnt++;
lCount++;
if (newln_cnt == 2)
{
parCount++;
newln_cnt = 0;
}
break;
case ' ':
pCount++;
break;
}
}
prom = (cCount / pCount);
printf("Total caracteres: %d \n", cCount);
printf("Cantidad palabras: %d \n", pCount);
printf("Cantidad líneas: %d \n", lCount);
printf("Cantidad párrafos: %d \n", parCount);
printf("Promedio longitud palabra: %f \n", prom);
return 0;
}
it kinda works with the characters (it shows one less). but the rest is all bad.
Input:
Oid, mortales, el grito sagrado:
"Libertad, libertad, libertad!"
Oid el ruido de rotas cadenas,
ved en trono a la noble igualdad.
Ya su trono dignisimo abrieron
las Provincias Unidas del Sud
y los libres del mundo responden:
"Al gran pueblo argentino, salud!
Al gran pueblo argentino, salud!"
Y los libres del mundo responden:
"Al gran pueblo argentino, salud!"
Sean eternos los laureles
que supimos conseguir,
que supimos conseguir.
Coronados de gloria vivamos...
o juremos con gloria morir!,
o juremos con gloria morir!,
o juremos con gloria morir!
Expected Ouput:
Total caracteres: 558
Cantidad palabras: 87
Cantidad líneas: 25
Cantidad párrafos: 8
Promedio longitud palabra: 4.966
my ouput:
Total caracteres: 557
Cantidad palabras: 69
Cantidad líneas: 24
Cantidad párrafos: 12
Promedio longitud palabra: 8.000
The program counts the number of characters, words, lines and paragraphs (two consecutive '\n'). and the averge word length .
Each your count conditions are wrong.
fix like follows:
#include <stdio.h>
#include <ctype.h>
int main(void){
int pCount=0, parCount=0, cCount=0, lCount=0;//word, paragraph, character, line
int abCount = 0;//alphabet
double prom=0;
int c;//It should be int.
char pprev = '\n', prev = '\n';
while ((c=getchar())!=EOF){
++cCount;
if(isalpha(c))
++abCount;
if(isspace(c)){
if(c == '\n'){
++lCount;
}
} else if(isspace(prev)){//isspace(prev) && !isspace(c) : edge of top of word
++pCount;
if(pprev == '\n' && prev == '\n'){//edge of top of paragraph
++parCount;
}
}
pprev = prev;
prev = c;
}
if(prev != '\n'){//If the file is not terminated by newline
++lCount;
}
prom = (double)abCount / pCount;//(cCount - spcCount - punctCount) / pCount
printf("Total caracteres: %d \n", cCount);
printf("Cantidad palabras: %d \n", pCount);
printf("Cantidad lineas: %d \n", lCount);
printf("Cantidad parrafos: %d \n", parCount);
printf("Promedio longitud palabra: %.3f \n", prom);
return 0;
}
I see several problem in your code:
Paragraphs count: you do not set newln_cnt to 0 if read character is different of \n. This will count one paragraph each time two \n are read.
Spaces count: you only consider ' ' characters, you may miss other white space characters like \t ou non breakable space. consider using isspace() function.
Mean line length: you divide two integers to get a float, consider casting:
prom = (float)cCount / (flao)pCount;
My advice: Start with a short text (3 words per line, 5 lines) and a debugger.
It didn't compile because of type conversion errors, but you can use floats for everything and it will compile:
#include <stdio.h>
int main(int argc, char const *argv[])
{
double pCount=0, parCount=0, cCount=0, lCount=0;
double prom=0;
char c;
int newln_cnt=0;
while ((c=getchar())!=EOF){
switch (c)
{
case '\n':
newln_cnt++;
lCount++;
if (newln_cnt == 2)
{
parCount++;
newln_cnt = 0;
}
break;
case ' ':
pCount++;
break;
}
}
prom = (cCount / pCount);
printf("Total caracteres: %f \n", cCount);
printf("Cantidad palabras: %f \n", pCount);
printf("Cantidad líneas: %f \n", lCount);
printf("Cantidad párrafos: %f \n", parCount);
printf("Promedio longitud palabra: %f \n", prom);
return 0;
}
Now that the program compiles, you can adjust to whatever types are best for you program, you might even have a type of your own.
A famous program that works like your program is wc - word count and is part of the standard Unix libraries.

caesar cipher in C, using arrays and chars, I get an error in the numbers

Here is the code, basically I gotta do the ceasar cipher in C using arrays and chars only, here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
main ()
{
char alfabeto[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int a=0;
int b=0;
int m=0;
int c=0;
//char letra;
int cont=0;
char k[]={};
printf("Introduzca un primer numero 'a':\n");
scanf(" %i", &a);
printf("Introduzca un segundo numero 'b':\n");
scanf(" %i", &b);
printf("Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):\n");
//Falta una validacion para la palabra.
for (int j=0;j<10;j++)
{
scanf(" %c",&k[j]);
cont=j; //cuenta la cantidad de elementos
if (k[j]=='.')
{
j=10;
}
}
for(int j=0;j<cont;j++) //Error in this bit I think.
{
for (int i=0;i<26;i++)
{
if (alfabeto[i]==k[j])
{
m=i;
i=26;
}
}
c = ( (a * m) + b );
printf("%c es: %i \t",k[j],c);
}
}
It uses a formula where c=(a*m+b).
m being the position of the original letter for example: A=0 then m=0.
a being a number you choose as well as b.
In my case I chose a=1 and b=3 and the word CESAR as the key word.
According to the formula the output number of each letter should be c.
The output should be:
C es: 5 E es: 7 S es: 21 A es: 3 R es: 20
Yet it is this:
WrongOutput
UPDATE:
I had to correct this:
char k[]={};
Into this:
char k[10]={'\0'};
Now I get the right output:
Right Output

Resources