Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In C language, is it possible to pass string as a case condition in switch case?
If possible, can AI (Artificial Intelligence) be achieved?
Is it possible to pass string as a case condition in switch case?
No - the switch statement only operates on integer values; case labels must be constant integral expressions. You'd have to map the string onto an integer value, either by using a hash function or a lookup table or something.
#define MAX_LEN 80 // or however long you need
#define HELLO_STRING some-integer-value
#define GOODBYE_STRING some-other-integer-value
#define NO_MAPPING 0
int mapToInteger( const char * str )
{
int mapValue = NO_MAPPING;
/**
* logic to map string to integer
*/
return mapValue;
}
int main( void )
{
char inputString[MAX_LEN];
...
while ( fgets( inputString, sizeof inputString, stdin ) )
{
switch( mapToInteger( inputString ) )
{
case HELLO_STRING:
process_hello();
break;
case GOODBYE_STRING:
process_goodbye();
break;
default:
case NO_MAPPING:
i_dont_understand();
break;
}
}
}
Will case or whitespace matter? In other words, should "THIS IS A TEST" and "This is a test" and "tHiS iS a TeSt" all give the same result? If so, then your mapToInteger function (or whatever you decide to call it) will have to take all that into account.
If possible, can AI (Artificial Intelligence) be achieved?
This is the programming equivalent of asking, "if I can use a hammer to nail two pieces of wood together, can I build an apartment complex?" Yeah, sure, but you need to do a bunch of other stuff as well.
The short answer is that a switch in C only accepts integer values, or something easy to cast to an integer (like a character).
There are workarounds tough, like using a hash function or using a series of “if”.
Concerning Artificial Intelligence, this is a vast field, that cannot be addressed with a simple switch. At least for a good result. You can have a look at expert systems as a start.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was making a script that is calculating the additions between two natural numbers which decimal lengths should be smaller or same with 10000, and printing a result of the sum.
Of course, there ain't any variable type that can hold a integer which length is 10000 in C.
So, I made the program by utilizing the simple additions' calculating logic that all we learn in a school when we were young. And also, I just should use strings to get those gigantic numbers.
But some results were starting with zero. I knew why did the zero appeared there, but I did prefer to have a result that is like "1234", not "01234". By the way, all other stuffs were perfect.
I needed a function that gets input as string, and erases a single zero starts with a string if it exists.
And could you make it instead of me, please? You should probably consider that the strings we will deal with can have such a length that is smaller or same with 10000.
Maybe this:
char * f( char * str )
{
while ( *str == '0' && str[1] )
str++; // skips all zero-s when it is not last character in string
return str;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
For example, I have this string:
ABABcct
Can I copy
ABc
begin index = 2, end index = 4
...from that string?
Is there any specific built-in function that can do this?
I know strncpy() can copy a number of characters of a string starting from the beginning of the string onto another. But I don't think it can do what I have just described. As far as I know, its "begin index" is limited to 0.
Actually you can use the function strncpy() with a pointer to anywhere in your string, not only a pointer to its beginning.
Example:
char *src = strdup("ABABcct");
char *dest;
strncpy(dest, src + 2, 3) // Copies 3 characters from your pointer src + 2 to your pointer dest
If you run this code, dest will contain ABc.
While in your case the standard copy functions would eventually work, their use is not allowed when the source and the destination are overlapped, in which case you'll experience an UB.
For such issue the standard C library provide the function memmove designed to handle overlapped areas. It works as using an intermediate buffer to solve any overlapping problem.
see also Meaning of overlapping when using memcpy
With strncpy
#include <stdio.h>
#include <string.h>
int main(void)
{
char p[10],s[10]="abcdefgh";
strncpy(p,s+2,3);
puts(p);
return 0;
}
I know strncpy() ... As far as I know, its "begin index" (as I call it) is limited to 0.
You knew it wrong. It's not about begin index or anything - simply you need to pass relevant char* in src and target which is being done here.
To add further clarification - most standard library functions which you are talking about never put a constraint of passing the pointer to the 0-th index. It doesn't matter which index you send - you can send 100th or 50th doesn't matter as long it follows the things expected by function (null termination etc).
The code posted here is for illustration purpose - didn't include the necessary checks needed to use str*cpy functions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this code that will print numbers from 0 to 9 in english words (like one for 1, two for 2, etc.). What if I wanted to print 374? Or something much larger, like 7549846451?
#include <stdio.h>
int main()
{
double sum;
if(scanf("%1f",&num)!=0)
{
if(num=(int)num)
{
switch((int)sum)
{
case 0:printf("zero\n");break;
case 1:printf("one\n");break;
case 2:printf("two\n");break;
case 3:printf("three\n");break;
case 4:printf("four\n");break;
case 5:printf("five\n");break;
case 6:printf("six\n");break;
case 7:printf("seven\n");break;
case 8:printf("eight\n");break;
case 9:printf("nine\n");break;
default:printf("not a digit"); break;
}
}else
{
printf("Invalid")
return 0;
}
}
return 0;
}
This is a good start, but it would take a lot more to complete your program:
Start by expanding your code to printing numbers 10..99. There would be a special case for 11..19, but after that it's pretty regular. The lower 20 can be addressed with a lookup table. In fact, making a look-up table for the whole range wouldn't be too bad, either.
With a routine that writes out numbers 0..99 in hand you can expand into hundreds by looking at the third digit the right, writing it out, adding "hundred", and proceeding to writing out the number 0..99
Now that you have a routine for writing out three-digit numbers all you need is to split your number into groups of tree, calling this routine for non-zero groups, and adding "billion", "million", and "thousand" corresponding to the rank of the group.
Here you have the solution to your problem. It is even the same example as you have pasted here, so if you have read the comments below, you'd have seen the comment form Bheema in which he posted the whole code for it.
Also, you can try writing your own code, it's not that hard. dasblinkenlight gave you instructions how to do it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a code for solving arithmetic expression like:4+3-2*6*(3+4/2)
For that I need to compare the operators in the string with precedence like:
1. ( or )
2. * or /
3. + or -
Can someone tell me how to compare two characters. As their ASCII values are not in the order which I want!
Use a lookup table. If using ASCII, it is just a 256 element table. You index it with the char.
For that I need to compare the operators in the string with precedence
like:
You can do something like this to get a precedence for each character:
int get_precedence (char c) {
switch (c) {
case '+':
case '-': return 3;
case '*':
case '/': return 2;
case '(':
case ')': return 1;
default: return -1;
}
}
That makes it very easy to add in additonal characters as you need.
However, you'll still have some issues. For example, how will you tell unary negation from subtraction? You'll need to look at context for that, because the answer will depend on what comes before. Dealing with infix notation is hard.
To do this yourself, you'll want to write a recursive descent parser or use the shunting yard algorithm. Either way, it'll be several hundred lines of hard code. Then you'll need to decide if you evaluate from the abstract syntax tree or compile to byte code.
I am writing a code for solving arithmetic expression
like:4+3-2*6*(3+4/2)
If you want to solve that in an easy way, you should find a pre-existing library. TinyExpr is one such solution. It's open-source and contained in a single C source code file. Code for that would look like:
#include "tinyexpr.h"
double answer = te_interp("4+3-2*6*(3+4/2)", 0);
Even in ASCII, the order of the integers are still the same. You can compare single digits. For example:
if ('7' > '2') will evaluate to true
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am trying to program an encrptor and decryptor. My problem is a pointer that I assigned value first still has the same value as the second. I tried to use free but the problem is still the same.
For example, I typed aslkdjlasc(sample only)
and the output would be:
helloworld
I try to run the program again, then I type daskjda
the output would be like
doctorxRLD
RLD is from the past value of this pointer. It's supposed to be 7 characters only, but since helloworld is 10, the first 7 letters are replaced by the encryption but the last 3 characters are still printed.
What do I do?
UPDATE: HERE IS PART OF THE CODE:
void encrypt(char *crypt)
{
char *plaintext,*encryption,slash=0x2F;
int i,j,k,flags,f;
encryption=(char *)malloc(sizeof(int));
plaintext=(char *)malloc(sizeof(int));
printf("Enter plaintext, spaces,commas,and dots should be represented as /:\n");
scanf("%s",&*plaintext);
for(i=0;i<strlen(plaintext);i++)
{
j=1;flags=0;
while(j<53 && flags==0)
{
if(plaintext[i]==slash)
{
encryption[i]=slash;
flags=1;
}
if(plaintext[i]==crypt[j])
{
encryption[i]=crypt[j-1];
flags=1;
}
k=j+2;
j=k;
}
}
printf("%s",encryption);
free(encryption);
free(plaintext);
getch();
}
HERE IS THE MAIN
main()
{
char c;
int timer;
char crypt[53]="***i have hidden my encryption code***";
clrscr();
printf("Press e to encrypt, d to decrypt, ESC to exit.\n");
c=getch();
switch(c)
{
case(0x1b):
exit(0);
break;
case(0x64):
decrypt(crypt);
break;
case(0x65):
encrypt(crypt);
break;
default:
printf("INVALID. FORCE EXIT IN 3 SEC0NDS.");
delay(3000);
exit(0);
}
getch();
}
In your code you are allocating integer size (4 bytes ) of memory for a string
When you do
plaintext=(char *)malloc(sizeof(int));
Then by doing this
scanf("%s",&*plaintext);
your are possibly scanning a string of size more than that four characters ( however you allocated only four bytes) also
scanf("%s",&*plaintext); is equivalent to scanf("%s",plaintext); ( with the previous statement you are adding unnecessary computations.
it's me. I got it already. Thanks to all your comments though some are harsh. haha
I refrained from using malloc because apparently DCoder points out I do not know how to use them.
Thanks Sanyam Goel I have fixed my scanf too.
I used only 2 pointers instead of 4. What I did was I instantiated them in the main function instead of in each of the decrpyt and encrypt functions. Like this:
main()
{
char c,*from, *to; ..........
void encrypt(char *crypt,char *plaintext,char *encryption)
void encrypt(char *crypt,char *ciphertext,char *decryption)
So when I call either of them, I just put:
case(0x64):
decrypt(crypt,from,to);
break;
case(0x65):
encrypt(crypt,from,to);
break;
And at the end of the switch in the main function:
free(from); from=NULL;
free(to); to=NULL;
So now I have eliminated unnecessary pointers and extra processes.
THANK YOU EVERYONE. :)