I just have written a program which suppose to return char which appears the most/least. Program work during the testing without switch statement, but when I added it start to crash. Can you have a look?
Main function
#include <stdio.h>
#include <stdlib.h>
#include "tools.h"
int main(int argc, char *argv[]) {
int count[256] = { 0 };
int c;
while ( (c=getchar())!=EOF ){
count[c]++;
}
switch (argv[1][1]) {
case 'm': case 'M':
mostOften(count);
break;
case 'l': case 'L':
leastOften(count);
break;
default:
mostOften(count);
break;
}
return 0;
}
Tools function
#include <stdio.h>
#include <stdlib.h>
#include "tools.h"
void mostOften(int *s) {
int j;
int max, cha;
for(j=32; j<126; j++){
if(s[j]>max) {
max=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, max);
}
void leastOften(int *s) {
int j;
int min=10000, cha;
for(j=32; j<126; j++){
if(s[j] && s[j]<=min) {
min=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, min);
}
You are using max uninitialized, thus, reading garbage:
int max, cha;
for(j=32; j<126; j++){
if(s[j]>max) {
Also, you need to check if argv[1][1] exists before using it:
switch ((argc > 1 && argv[1][0]) ? argv[1][1] : 0) {
Related
I tried to make a calculator using stack but it works partially (that is, sometimes when I insert larger number the answer is wrong but for small numbers generally correct).I don't know may be there is some undefined behaviour in my code (and also some charachter is getting swapped somewhere see I have mentioned it in my code comment). What is wrong in it.
My code:
#include <stdio.h>
#include <string.h>
#include "stackforcalc.h"
int isOperand(char b){
if(b>='0' && b<='9'){
return 1;
}else{
return 0;
}
}
int isOperator(char b){
if(b=='+' || b=='-' || b=='*' || b=='/'){
return 1;
}
return 0;
}
int getwt(char b){
int g=-1;
switch (b)
{
case '+':
case '-':
g=1;
break;
case '/':
case '*':
g=28787868;
break;
}
return g;
}
int higherprecedence(char a,char b){
int c=getwt(a);
int d=getwt(b);
return (c>=d)?1:0;
}
int infToPost(char *b,char *str){
int j=0;
for(int i=0;i<strlen(b);i++){
if(b[i]== ' ' || b[i]== ',' ){
continue;
}
else if(isOperator(b[i])){
str[j]=' ';
j++;
while(!empty() && gettop() != '(' && higherprecedence(gettop(),b[i])){
str[j]=gettop();
j++;
pop();
}
push(b[i]);
}
else if(isOperand(b[i])){
str[j]=b[i];
j++;
}
else if(b[i]=='('){
push(b[i]);
}
else if(b[i] ==')'){
while(!empty() && gettop() != '('){
str[i]=gettop();
j++;
pop();
}
pop();
}
}
while(!empty()){
str[j]=gettop();
j++;
pop();
}
}
int Evaluate(int t,char y,int r){
int ty;
switch(y){
case '+':
ty=t+r;
break;
case '-':
ty=r-t; //I inverted these.
break;
case '*':
ty=r*t;
break;
case '/': //I inverted these because
ty=r/t; //even though I did t/r it performed r/t.
break; //may be somewhere before the numbers were swapped
default:
ty=-1;
break;
}
return ty;
}
int calculatepostfix(char *c){
for(int i=0;i<strlen(c);i++){
if(c[i]==' ' || c[i]==','){
continue;
}
else if(isOperator(c[i])){
int op1=gettop2();
pop2();
int op2=gettop2();
pop2();
int oper=Evaluate(op1,c[i],op2);
push2(oper);
}
else if(isOperand(c[i])){
int res=0;
while(i<strlen(c) && isOperand(c[i])){
res=(res*10)+(c[i]-'0');
i++;
}
i--;
push2(res);
}
}
return gettop2();
}
int main(){
char b[65];
printf("\n \n**-- Calculator --**\n");
printf("Enter expression: ");
fgets(b,sizeof(b),stdin);
char str[50];
infToPost(b,str);
int tt =calculatepostfix(str);
printf("Your answer is: %d",tt);
}
The code in "stackforcalc.h" is
#ifndef stacycalc
#define stacycalc
#define maxsize 50
char a[maxsize];
int top=-1;
int abc[maxsize];
int to=-1;
void push2(int re){ abc[++to]=re; }
void push(char b){ a[++top]=b; }
void pop2(){ to--; }
void pop(){ top--;}
int gettop2(){ return (to==-1)?-1:abc[to]; }
char gettop(){ return (top==-1)?0:a[top]; }
int empty(){ return (top==-1)?1:0; }
#endif
In infix to postfix function, in place of str[i]=gettop();, there should be
str[j]=gettop(), so the expression entered inside the brackets can be processed. Also add this piece of code after fgets to remove the '\n' that fgets may append.
fgets(b,sizeof(b),stdin);
for(int i=0;b[i]!='\0';i++){ // removes \n added by fgets
if(b[i]=='\0'){
if(b[i-1]=='\n'){
b[i-1]='\0';
}
}
}
Somebody know how to make char str[20]="reviver",palind=1 be true printf("%s eh palindromo.\n",str)?
My code below
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]="reviver",palind=1;
int tam = strlen(str);
int i=0; char cont = tam;
for(; i <= cont; i++,cont--)
{
if(str[i]!=str[cont])
{
palind=0;
break;
}
cont--;
}
if(palind)
printf("%s eh palindromo.\n",str);
else
printf("%s nao eh palindromo.\n",str);
return 0;
}
I hope if you do two corrections in line numbers 7 and 15 as below, you may get expected result.
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]="reviver",palind=1;
int tam = strlen(str);
int i=0; char cont = tam-1;
for(; i <= cont; i++,cont--)
{
if(str[i]!=str[cont])
{
palind=0;
break;
}
/*cont--;*/
}
if(palind)
printf("%s eh palindromo.\n",str);
else
printf("%s nao eh palindromo.\n",str);
return 0;
}
I'm beginer in C/C++ programming.
This is my program that displays binary numbers in ascending order in the terminal (I'm compiling in Linux Mint).
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2];
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}
This is what I see in the terminal
Where did this symbol come from? How to solve it?
C strings are null terminated.
The %s specifier searches for a null termination.
In your case it keeps on printing until it finds one, so you get some random symbols.
Try making use of null character at the end of the string and check.
Have a look at the following implementation:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2 + 1]; //Increased size by 1 for null character
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
naborStr[bitCount*2 +1] = '\0'; //Appending null character
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}
I have use this code to use switch case for a string
#define BADKEY -1
#define b 1
#define s 2
#define r 3
#define p 4
typedef struct { char *key; int val; } t_symstruct;
static t_symstruct lookuptable[] = {
{"b",b},{"s",s},{"r",r,{"p",p}
};
#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))
int main () {
what is a mistake here?
int keyfromstring(char *key)
{
int i;
for (i=0; i < NKEYS; i++) {
if (strcmp(lookuptable[i].key, key) == 0)
return lookuptable[i].val;
}
return BADKEY;
}
switch case in c
switch (keyfromstring(field1))
{
case b :
printf(" is b\n" );
break;
case s :
printf("is s\n" );
break;
case r :
printf(" is r\n" );
break;
case ps:
printf("is p\n" );
break;
case BADKEY:
printf("Case: BADKEY \n");
break;
default://case if nothing
printf("Case: nothing happen\n");
}
**I got this message error segmentation fault(core dumped)
after printing some lines correctly,so please what can be the error here?
check the field1 before passing to the function there could be some issue with that. I am not seeing any error here . plus you did not clearly mention when it will crash
if you got the error segmentation fault(core dumped) once at the end of printing the switch case .you could be getting null at the end
check if feild1 is null .
The lookuptable has typos, it should like:
static t_symstruct lookuptable[] = {
{"b",b}, {"s",s}, {"r",r}, {"p",p}
};
Your original version will not even compile. The testing program is presented below:
#include <stdio.h>
#include <string.h>
#define BADKEY -1
#define b 1
#define s 2
#define r 3
#define p 4
typedef struct {
char *key;
int val;
} t_symstruct;
static t_symstruct lookuptable[] = {
{"b",b}, {"s",s}, {"r",r}, {"p",p}
};
#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))
int keyfromstring(char *key)
{
int i;
for (i=0; i < NKEYS; i++) {
if (strcmp(lookuptable[i].key, key) == 0)
return lookuptable[i].val;
}
return BADKEY;
}
int main (void) {
char * arr[] = { "b","s","r", "p", "!", NULL} ;
int i;
for (i =0; arr[i] !=NULL; i++)
{
switch (keyfromstring(arr[i]))
{
case b :
printf("%s is b\n", arr[i] );
break;
case s :
printf("%s is s\n", arr[i] );
break;
case r :
printf("%s is r\n", arr[i] );
break;
case p:
printf("%s is p\n", arr[i] );
break;
case BADKEY:
printf("Case: BADKEY: %s \n", arr[i] );
break;
default://case if nothing
printf("Case: nothing happen\n");
break;
}
}
return 0;
}
Test:
b is b
s is s
r is r
p is p
Case: BADKEY: !
I'm pretty new to C so be gentle, somewhy my code doesn't work, be kind and help my figure it out why it doesn't, also if it's possible to make it shorter without making it too complicated, please help in that too.
main.c
#include <stdio.h>
#include <stdlib.h>
#include "swap.h"
#include "magic.h"
int main(int argc, char *argv[])
{
int i,j,count;
int min=atoi(argv[1]);
int max=atoi(argv[2]);
if(min>max)
{
swap(&min, &max);
}
if (min<0)
{
min=1;
}
if(argc<2 || argc>5){exit(EXIT_FAILURE);}
else
{
magic();
}
}
Magic.c
#include <stdlib.h>
#include <stdio.h>
#include magic.h
magic(char *argv[])
{
for(i = min; i<=max; i++)
{
count = 0;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
return 0;
}
this is as single file for simplicity
#include <stdio.h>
#include <stdlib.h>
void swap(int *a,int *b){
int c=*a;
*a=*b;
*b=c;
}
void magic(int min, int max);
int main(int argc, char *argv[])
{
int min,max;
if(argc!=3) // (argc<2 || argc>5)
exit(EXIT_FAILURE);
min=atoi(argv[1]);
max=atoi(argv[2]);
if(min>max)
swap(&min, &max);
if (min<0)
min=1;
magic(min,max);
return EXIT_SUCCESS;
}
void magic(int min, int max){
int i,j,count;
for(i = min; i<=max; i++){
count = 0;
for(j=2; j<=i/2; j++) {
if(i%j==0){
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
}
You have some error in your code :
you are trying to use the variables min, max and countin your function magic however since they are declared in your main function magic does not have knowledge of them.
you should change your main function like :
#include <stdio.h>
#include <stdlib.h>
#include "swap.h"
#include "magic.h"
int main(int argc, char *argv[])
{
int min=atoi(argv[1]);
int max=atoi(argv[2]);
if(min>max)
{
swap(&min, &max);
}
if (min<0)
{
min=1;
}
if(argc<2 || argc>5){exit(EXIT_FAILURE);}
else
{
magic(min, max);
}
return EXIT_SUCCESS;
}
and your magic function :
#include <stdlib.h>
#include <stdio.h>
#include "magic.h"
int magic(int min, int max)
{
int count;
for(int i = min; i<=max; i++)
{
count = 0;
for(int j=2; j<=i/2; j++)
{
if(i%j==0)
{
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
return 0;
}
In the main function I change magic(); by magic(min, max); to pass parameters to the function which can be retrieve in magic with it's new signature int magic(int min, int max).
Since your magic function return an integer don't forget to specify the return value in the signature of your function.