isalpha() function in C don't read - c

I'm trying to write the substitution cipher but, a part of it, in particular the one where it sees me if the inserted alphabet is composed only of text characters "a ... z", doesn't work me. Could you tell me why the isalpha function (alfabeto_sostitutivo), although I insert the normal alphabet, gives me 0 as a result? Thanks in advance for the time spent.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main () {
int caratteri_diversi_1 = 0, caratteri_diversi_2 = 0, b = 0, tutti_alpha = 0, alpha_minuscoli = 0, alpha_maiuscoli = 0;
char alfabeto_sostituzione [27];
printf ("Inserisci l'alfabeto di criptazione (inglese):\n");
fgets (alfabeto_sostituzione, sizeof(alfabeto_sostituzione), stdin);
if (strlen(alfabeto_sostituzione)==26) //se la lunghezza dell'alfabeto sostitutivo è giusta
{
printf("I due alfabeti sono lunghi uguale\n");
for (int c=0; alfabeto_sostituzione[c] != '\0'; c++)
{
if (isalpha(alfabeto_sostituzione[c])==1)
alpha_minuscoli++;
else if (isalpha(alfabeto_sostituzione[c])==2)
alpha_maiuscoli++;
}
tutti_alpha = alpha_minuscoli + alpha_maiuscoli;
printf("alpha_minuscoli: %d\n",alpha_minuscoli);
printf("alpha_maiuscoli: %d\n",alpha_maiuscoli);
printf("tutti_alpha: %d\n",tutti_alpha);
if (tutti_alpha < 26 )
printf("L'alfabeto inserito NON contiene solo caratteri dell'alfabeto\n");
}
}
By filling in the program, the following text is returned:
Inserisci l'alfabeto di criptazione (inglese):
abcdefghijklmnopqrstuvwxyz
I due alfabeti sono lunghi uguale
alpha_minuscole: 0
alpha_maiuscole:0
tutti_alpha: 0
L'alfabeto inserito NON contiene solo caratteri dell'alfabeto

isalpha(argument) and other related functions declared in ctype.h
return a non-zero(true) if the argument satisfies the condition
described, and zero(false) if not.
Since you are checking for lower and upper case characters, the ctype library already has functions islower(argument) and isupper(argument) defined.
You could use them in tandem with the isaplha function, like so......
for (int c=0; alfabeto_sostituzione[c] != '\0'; c++)
{
if (isalpha(alfabeto_sostituzione[c]))
{
if(islower(alfabeto_sostituzione[c]))
alpha_minuscoli++;
else
alpha_maiuscoli++;
}
}

Related

How to compare the value of a phrase within a table with a letter?

I need to create a function that is given a table with different phrases and I must print the first phrase on the table that ends in "n". How would I go about this?
So far I have the table with three phrases with the second one ending in "n". Ive tried different things for the last hour but I'm new to C and it is tricky.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char TTablaFrases[5][80]; //una tabla de 10 frases
int FraseAcabadaEnN (TTablaFrases tabla)
{
}
int main(void) {
TTablaFrases miTabla;
strcpy (miTabla[0], "First phrase");
strcpy (miTabla[1], "Second phrase n");
strcpy (miTabla[2], "Third phrase");
}
If ends in 'n' means the last letter than this would do.
char TTablaFrases[5][80] degrades to a char *TTablaFrases[80] when passed to a function, so you need to pass in the length of your table or use a sentinel (empty string aka '\0') to signify end of the table.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char TTablaFrases[5][80]; //una tabla de 10 frases
int FraseAcabadaEnN(TTablaFrases tabla) {
for(size_t i = 0; *tabla[i]; i++) {
size_t l = strlen(tabla[i]);
if(tabla[i][l-1] == 'n')
return i;
}
return -1;
}
int main(void) {
TTablaFrases miTabla;
strcpy(miTabla[0], "First phrase");
strcpy(miTabla[1], "Second phrase n");
strcpy(miTabla[2], "Third phrase");
miTabla[3][0] = '\0';
int i = FraseAcabadaEnN(miTabla);
if(i >= 0)
printf("%s\n", miTabla[i]);
}
and it prints:
Second phrase n
The function needs to loop over each row of the array, skipping rows that contain no information.
For rows that contain text, the last character is tested as being the letter 'n'.
The index of the first row that meets this criteria is returned to the caller,
else an impossible value is returned to indicate no rows matched the criteria.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// incorrect comments are disturbing
typedef char TTablaFrases[5][80]; // una tabla de frases
int FraseAcabadaEnN( TTablaFrases tabla ) {
// check each 'entry'
for( size_t i = 0; i < sizeof *tabla/sizeof *tabla[0]; i++ )
// is there something to check on this entry?
if( tabla[i][0] )
// is the last character 'n'?
if( tabla[i][ strlen( tabla[i] ) - 1 ] == 'n' )
// return this table index
return i;
// return impossible 'index' indicating "not found"
return -1;
}
int main() {
TTablaFrases miTabla = { 0 }; // ALWAYS intialise ALL variables
strcpy( miTabla[0], "First phrase" );
strcpy( miTabla[3], "Second phrase n" ); // NOTE! putting into array element #3
strcpy( miTabla[2], "Third phrase" );
int i = FraseAcabadaEnN( miTabla );
if( i >= 0 )
printf( "Elem #%d - %s\n", i, miTabla[i] );
return 0;
}
Output
Elem #3 - Second phrase n
ALWAYS initialise variables. Uninitialised variables are a source of many bugs.

C: variables retain the value from previous operation instead of resetting

I am fairly new to C and have been trying my hand with some arduino projects on Proteus. I recently tried implementing a keypad and LCD interface with Peter Fleury's libraries, so far the characters I input are displayed fine, but I run into a problem when trying to print to the serial port. It's like the value of the keys keeps on being concatenated with every iteration so the ouput has extra characters like this:
The value before the comma is from the 'key' variable, the value after it the 'buf' variable:
151
(The 5 I input in the second iteration was added to the 1 from the first iteration and then put into the variable I print)
I figure it may be due to my lack/incorrect use of pointers, heres is my code:
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <stdio.h>
#include "lcd.h"
#include "mat_kbrd.h"
#include "funciones.h"
#include "menu.h"
char buf[256];
char* coma = ",";
int main(void)
{
pin_init();
serial_begin();
lcd_init(LCD_DISP_ON);
kbrd_init();
bienvenida();
while (1) {
int i = 0;
char key = 0;
//char *peso;
//int pesoSize = 1;
char peso[100];
//peso = calloc(pesoSize,sizeof(char));
int salida = 0;
lcd_clrscr();
desechos();
key = kbrd_read();
if (key != 0) {
lcd_gotoxy(0,3);
lcd_putc(key);
_delay_ms(2000);
lcd_clrscr();
cantidad();
while (salida != 1) {
char keypeso = 0;
keypeso = kbrd_read();
//pesoSize = i;
//peso = realloc(peso,pesoSize*sizeof(char));
if (keypeso != 0) {
if (keypeso == '+') {
salida = 1;
keypeso = *("");
lcd_clrscr();
calcularTotal(key,peso);
_delay_ms(2000);
} else {
lcd_gotoxy(i,1);
lcd_putc(keypeso);
snprintf(peso, sizeof peso, "%s%s",peso, &keypeso);
//strcat(peso,&keypeso);
i++;
_delay_ms(2000);
}
}
}
snprintf(buf, sizeof buf, "%s%s%s", &key,coma,peso);
serial_println_str(buf);
}
}
}
&key and &keypeso point to a single char, but you are using the %s format specifier, so trying to read a string into a single char. Use %c rather then %s for single characters, and pass the char not the address-of-char..

What am I doing wrong with this array in C?

I need to know how many times does "Maria" appears in this array, but when I run it, it says that it appears 51 times, and I think its only like 8
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int g;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i>40; i++)
{
printf("%s\n", nombres[40]);
if(nombres[i] == "Maria")
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
system("pause");
return 0;
}
if(nombres[i] == "Maria")
You can't compare strings like this. You need to use strstr() to look for substrings in a string.
Also,
printf("%s\n", nombres[40]); probably should have i instead of 40. And your comparison in the middle of your for loop above this is backwards.
And... probably more else wrong, but that is enough for me.
There are lots of error..... Let's see how much I could solve..xd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int g=0;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i<40; i++)
{
printf("%s\n", nombres[i]);
if(!strcmp(nombres[i],"Maria"))
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
return 0;
}
Here the counter variable g was not initialized. It should be initialized to 0 otherwize it contains some garbage value.then in for loop the condition was wrong the loop was not being executed because u write I>40 here i is initialized by 0 so condition get false and loop don't run.then printf in the loop contains nombres[40] which gives a nullpointer because you last name is hombres[39].then in if condition you can't just compare string like other variable you have to use lib function which is strcmp which means string compare.
In following conditions
strcmp(s1,s2);
**
*if s1==s2 then it returns 0.
If s1>s2 then it returns 1
If s1<s2 it returns -1
So I wrote !strcmp();
So if string matches it will return 0 and '!' Converts it to 1.
Hope this works.kudos.

regex in C language using functions regcomp and regexec toggles between first and second match

I am using Dev-c++ IDE to compile my C (WIN32 API) programs.
I am using regex lirary provided by http://gnuwin32.sourceforge.net/packages/regex.htm
I am using this documentation for reference and the same has been provided from the above site... http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html
Following is the Code:
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <regex.h>
#include <conio.h>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
int a;
regex_t re;
char str[128] = "onces sam lived with samle to win samile hehe sam hoho sam\0";
regmatch_t pm;
a = regcomp(&re,"sam", 0);
if(a!=0)
{
puts("Invalid Regex");
getch();
return 0;
}
a = regexec(&re, &str[0], 1, &pm, REG_EXTENDED);
printf("\n first match at %d",pm.rm_eo);
int cnt = 0;
while(a==0)
{
a = regexec(&re, &str[0] + pm.rm_eo, 1, &pm, 0);
printf("\n next match %d",pm.rm_eo);
cnt++;
if(cnt>6)break;
}
getch();
return EXIT_SUCCESS;
}
The while loop goes infinite displaying the first and second end position of the matching string and not going further.
I have used the cnt variable to check for 6 turns and then i am breaking the loop to stop the infinite run.
The Output is:
first match at 9
next match 15
next match 9
next match 15
next match 9
next match 15
What am i missing here?
Try this instead:
int cnt = 0;
int offset = 0;
a = regexec(&re, &str[0], 1, &pm, REG_EXTENDED);
while(a==0) {
printf("\n %s match at %d", offset ? "next" : "first", offset+pm.rm_so);
offset += pm.rm_eo;
cnt++;
a = regexec(&re, &str[0] + offset, 1, &pm, 0);
}
You were not actually stepping through your string, which was what caused the unending loop.
I come up with this code, giving a little improvement (more compact) of the #jxh solution, and avoiding of using extra lookup &str[0]
int cnt = 0;
int offset = 0;
while(!regexec(&re, str + offset, 1, &pm, REG_EXTENDED)) {
printf("%s match at %d\n", offset ? "next" : "first", offset+pm.rm_so);
offset += pm.rm_eo;
cnt++;
}

Stack overflow with pointers in C

I'm new in C, and I'm trying some exercises that I found.
In one of the exercises I'm trying to use a pointer to a string (a char array), but it doesn't work. It compiles, but when is executed, it throws "stack overflow" (well, I think is an "stack overflow" because I have it in spanish).
These are the problematic lines:
//This is the variable declaration, before this, there is the "main function" declaration
char entrada[100];
char *ult=entrada;
char cantidadstr[10];
int i,j,k = 0;
int res;
scanf ("%s",entrada);
printf ("\n%s",entrada);
//Here crashes
printf ("Hola %s",ult);
while (*ult != "\0"){
//And here there's more code
Thank you in advance!!
EDIT
(I can't answer me :))
Then, I'll post a bit more of code.
When I execute, after inserting data, it throws "Violación de segmento", and google says that means Stack Overflow
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void){
char entrada[1001*11*101];
/*Asi tenemos el tamano maximo:
1001 por las 1000 posibles lineas, mas la primera
11 por el tamano maximo del numero (1 + 9 ceros), mas el espacio o salto de linea siguiente
101 por el numero de numeros por linea, mas el primero
*/
char *ult=entrada;
char cantidadstr[10];
int i,j,k = 0;
int res;
memset (entrada,'\0',1001*11*101);
scanf ("%s",entrada);
printf ("\n%s",entrada);
//poniendo ese print ahi arriba, ese me lo muestra, por tanto, el fallo esta en el puntero de debajo de esta linea
printf ("Hola %s",ult);
while (*ult != "\0"){
if(*ult == "\n"){
if(i != 0){
printf("\n");
}
i++;
j = 0;
}
else if(i != 0){
if(*ult == " "){
j++;
k=0;
res = atoi(cantidadstr);
printf("%d ",res*2);
//Este es el otro cambio que hablaba
cantidadstr[10] = '\0';
}
else if(j != 0){
cantidadstr[k] = *ult;
}
}
k++;
*ult++;
}
return 0;
}
This is the exact and full code, with comments in spanish for another forum. The size of "entrada" is big enough for any data send in the exercise. The "memset" is just added. The second comment shows where it crashes
Thank you for your quick answer!!
The code before the while loop is fine as it compiles and runs correctly(as far as i can think)
But the while loop has an error i'm not sure how it compiled in your case.
because you have written
while (*ult != "\0"){
which gives compiler error as
*ult is of type char
"\0" is of type const char*
you have to convert "\0" to '\0'
The following line:
cantidadstr[10] = '\0';
will write past the end of cantidadstr, which is definitely bad and most likely causing your stack overflow. If you want to null terminate cantidadstr, use cantidadstr[9]= '\0';. Arrays in C are zero based, not one based, so the first element of an array of size N starts at [0] and the last referenceable element is [N-1].

Resources