How to identify a sequence in C - c

I would like to ask how to identify a sequence in C for example AAAAA & ddddd the sequence is all of the inputted characters must be the same.. How is it possible to achieve that? Do I need to use char ? Here is what i had try
#include<stdio.h>
int main() {
char ch;
scanf("%cccc", &ch);
if (ch = 'c')
printf(&ch);
else
printf("Character is Not the same sequence");
return (0);
}

To compare two characters:
char a = 'a';
char b = 'b';
return a == b; // this compares integer values of two characters
// and returns 1/0 if they do match/do not match
To compare strings:
char str1 = "AAAAA";
char str2 = "aaaaa";
return strcmp(str1, str2);
man strcmp(3):
The strcmp() function compares the two strings s1 and s2. It returns
an integer less than, equal
to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater
than s2.
The strncmp() function is similar, except it compares the only first (at most) n bytes of s1 and
s2.
Your code contains few bugs. %c format is for scanning single character, use %s for strings. Here:
if (ch = 'c')
you assigned 'c' to ch, not what you wanted. Use == in C for comparisons.

I would try this:
Accept a string as input (instead of a character)
Set up a loop to walk through the string, character by character
Your first character will be the "good" value
If at any time, you encounter a different character, fail out of the loop
If you reach the end of the string without failing, you succeed

Create a Macro for the pattern you want to find. typecast your input to the size of the pattern you want to recognise. Subtract both. If 0 pattern matched. Else,shift right 1 bit and repeat. Example, Pattern to find #define wPAT 0x1234. Input=> U32 dwInput=0x12345678. Result= (U16)dwInput - wPAT . If 0,pattern found. Else, dwInput>>1 and repeat Result= (U16)dwInput - wPAT. Repeat 16 times to find if pattern is present or not

Related

Scanf for a word in C language

Hey I got this code where I need to scanf the input of the user (ANO/NE) and store this input into variable "odpoved". How to do that? What I have now looks like it is scanning just the first letter of the input.
char odpoved;
printf("Je vše v pořádku? (ANO/NE)");
scanf("%s", &odpoved);
if(odpoved == "ANO" || odpoved == "ano"){
printf("Super, díky mockrát");
}
else if(odpoved == "NE" || odpoved == "ne"){
printf("To mě mrzí, ale ani já nejsem dokonalý");
}
else{
printf("Promiň, ale zmátl jsi mě. Takovou odpověď neznám!!!");
return 0;
}
The first thing you should know about is that char is a data type consisting of 1 byte and is used to store a single character such as 'a', 'b', 1, 2 etc... there are 256 possible characters which are often represented by the ASCII table ( https://www.ascii-code.com/).
As odpoved is a string you need to make it type char* or equivalently char [] which is a pointer to the first char in the array (string) of characters. The last char in a string is always a terminator byte '\0' used to indicate the end of a string. The null terminator is automatically inserted when the speech marks are used e.g. "sometext" or when %s is used to get input.
The other mistake you have made is to compare strings with == or != signs. This will not work as the first characters will be compared with each other. Hence to compare the characters you will need to use strcmp function provided when the string.h library is included. There are many other useful string functions such as strlen which tell you the length of the string etc.

Baffled by strcmp

I have a very simple function to convert a 3 char string representing a bit string to a decimal number:
int bin3_to_dec(char *bin) {
int result;
result=0;
printf("string: %s\n", bin);
printf("c0: %c\n", bin[0]);
printf("c1: %c\n", bin[1]);
printf("c2: %c\n", bin[2]);
if ((strcmp(&bin[0], "1") == 0))
result += 4;
if ((strcmp(&bin[1], "1") == 0))
result += 2;
if ((strcmp(&bin[2], "1") == 0))
result += 1;
printf("result: %d\n", result);
return result;
}
When I run the program and feed this function the string 111 it should calculate 7. Instead it outputs this:
string: 111
c0: 1
c1: 1
c2: 1
result: 1
Why is it not calculating the correct value? Why is only the third condition successfully passing?
Your string bin equal "111" really consists of four chars - that is '1', '1', '1', '\0' where the 4th char has the value zero which terminates (i.e. ends) the string.
So &bin[0] is the string "111"
and &bin[1] is the string "11"
and &bin[2] is the string "1"
So what your code is actually doing is the same as:
if ((strcmp("111", "1") == 0))
result += 4;
if ((strcmp("11", "1") == 0))
result += 2;
if ((strcmp("1", "1") == 0))
result += 1;
Only the last compare results in true so resultbecomes 1
&bin[0] is actually a pointer to a character array starting from 0th index which is 111. So, your first comparison fails. Similarly for second. But in your third comparison, &bin[2] is a pointer to character array starting from 2nd index which is 1 and hence it add 1 to result. So to make your code work:
you can check if(bin[0] == '1') // Here you compare the character at bin[0] and it is equal to 1 and so here the condition gets fulfilled.
C does not detect the end of a string until it encounters a null (i.e. \0). When you pass "111" into your function, you are actually passing a pointer to a block of memory that looks like this: "111\0". Thus, when you pass the address of bin[0] into strcmp(), strcmp operates on the full string "111". When you pass the address of bin[1] into strcmp(), strcmp operates on the string "11". Only when you pass the address of bin[2] into strcmp() do you get the behavior you were expecting, because in that case the next character in memory is a null.
if (bin[0] == '1') result += 4;
if (bin[1] == '1') result += 2;
if (bin[2] == '1') result += 1;
please note that &bin[0] is the same as bin
bin[0] is the first element
&bin[0] is a pointer to the first element just like bin
Have you tried printing &bin[1] (for example) as a string, instead of the individual characters? Because that's how strcmp() is going to see them.
In you do that, strcmp(&bin[0], "1") is clearly always non-zero, because &bin[0] is the full input string and (in our example) "111" is not at all like "1". Strings run until the null-terminator character.
You can use direct character comparisons (bin[0] == '1'), copy the character to a null-terminated string of its own, or (destructively) work from right to left and insert the null character ('\0') after the character that interests you. But you can't compare the middle of a string as a single character.
As mentioned by others, you are confusing those strings. The three of them are strings, however, string in java is an array of chars. So when you mean the string "1" using &bin[0], you are actually comparing "111". Why? Pointer to an array of chars make a string with the chars in this array starting where your pointer shows and continues to the end.
So when you point at the first letter you get "111", when you point at the second letter you get "11" and when you point at the last character you get "1", thats why your sum is 1. You can try to pass as argument the string "1111", you can see that your result is 0 intead of 1.
Your code seems somehow baffled around a function call of strcmp(), which isn't needed and would consistently return non-zero for any comparison between the string literal "1" and any "sub-string" pointed to in your code (&bin[0], &bin[1]), except for the one-printable-member-string &bin[2], if also "1". Let's have a walk-through.
As you have properly written in your function prototype, the pointer to the first element of the character array is being passed by value to your called function and copied as its argument. This is the "mechanism" for the part of memory populated by the array pointed to, to become visible by the called function, if its "upper bound" is known.
There are two means of having its upper bound known:
Passing the char array size as additional argument to the function, or
Null-terminating the char array in the calling function, so the called function can interpret it as string, which is your choice. The called function can either use strlen() to determine string length (size), or step through it, incrementing the counter, until a null-character is reached, and read size from the counter.
If the calling function already receives the array as a null-terminated string of '0' and '1' characters, the second looks more practical.
Allowing for up to as many characters as allowed by the storage capacity of the return data type of the called function (in this case int) clarifies the problem and simplifies the code. The caller function should guard against overflow.
The called function should only compare every array member's ASCII value with '1' and convert if equal.
For this strcmp isn't needed.
Please see the comments in this demonstration code, based on your post:
#include <stdio.h>
#include <string.h>
#define BPB 8 //bits per byte
int bin_to_dec(char *bin) //called function
{
int result=0;
int l = (int)strlen(bin);
for (int i = 0; i < l; i++){
printf("c%d: %c\n", i, bin[i]);
if(bin[i] == '1') //compare value of the i-th element
result += 1<<(l - i - 1); //convert to power-of-two and add to the result
}
return result;
}
int main(int argc, char *argv[]) //calling function
{
size_t siz = BPB*sizeof (int); //size for each char to represent one bit
char s[siz + 1]; //characters, each representing one bit + terminating '\0'
if((argc < 2)||(argc > 2)) //fail-safe check for correct count of arguments
return 1;
size_t len = strlen(argv[1]) ; //get length of the input string
if ( len > siz ) //check against too long input which would cause overflow
return 2;
strncpy(s, argv[1], len);
s[len] = '\0'; //appending the terminating null-character
for(int i = 0; i < (int)len; i++)
if((s[i] < '0')||(s[i] > '1')) //fool-proof check against 'off-limit' input
return 3;
printf("decimal: %d\n", bin_to_dec(s));
return 0;
}

What does strcmp return if two similar strings are of different lengths?

I understand that if you have 'cat' (string1) and 'dog' (string2) in strcmp (this is a C question) then the return value of strcmp would be less than 0 (since 'cat' is lexically less than 'dog').
However, I am not sure what would happen with strcmp if this happened:
string1: 'dog'
string2: 'dog2'.
What would strcmp return? Less than zero, zero, or greater than? For context, I am trying to write a comparator function that compares strings and would like to account for strings starting with the same characters. One string may have an extension (such as '2' in 'dog2' in the example above).
EDIT: This is not a duplicate question. The question that this is allegedly similar to asks what the return type represents - I am saying what happens when the strings are identical up to a point but then one of them stops whilst the other continues.
It returns the difference at the octet that differs. In your example '\0' < '2' so something negative is returned.
It is defined in the C standard as the difference between the first two non matching characters, but the implementation is wild. The only common point is that the return value is zero for equal strings, then respectively <0 or >0 for str1<str2 and str1>str2.
From ISO/IEC 9899:201x, §7.23.4 Comparison functions:
The sign of a nonzero value returned by the comparison functions
memcmp, strcmp, and strncmp is determined by the sign of the
difference between the values of the first pair of characters (both
interpreted as unsigned char) that differ in the objects being
compared.
But some implementations take care to return typical values as 0, 1 and -1. See i.e. the Apple implementation (http://opensource.apple.com//source/Libc/Libc-262/ppc/gen/strcmp.c):
int
strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
EDIT:
In the Android boot library for Donut-release (https://android.googlesource.com/platform/bootable/bootloader/legacy/+/donut-release/libc/strcmp.c) the function returns 0 if strings are equal and 1 for the other 2 cases, and are used only logical operations:
int strcmp(const char *a, const char *b)
{
while(*a && *b) {
if(*a++ != *b++) return 1;
}
if(*a || *b) return 1;
return 0;
}
C11 quotes
C11 N1570 standard draft
I think "dog" < "dog2" is guaranteed by the following quotes:
7.23.4 Comparison functions
1
The sign of a nonzero value returned by the comparison functions memcmp, strcmp,
and strncmp is determined by the sign of the difference between the values of the first
pair of characters (both interpreted as unsigned char) that differ in the objects being
compared.
So the chars are interpreted as numbers, and '\0' is guaranteed to be 0:
Then:
7.23.4.2 The strcmp function
2
The strcmp function compares the string pointed to by s1 to the string pointed to by
s2.
says that, obviously, strings are compared, and:
7.1.1 Definitions of terms
1 A string is a contiguous sequence of characters terminated by and including the first null
character.
says that the null is part of the string.
Finally:
5.2.1 Character sets
2 [...] A byte with
all bits set to 0, called the null character, shall exist in the basic execution character set; it
is used to terminate a character string.
so '\0' is equal to zero.
Since the interpretation is as unsigned char, and all chars are different, zero is the smallest possible number.
From man strcmp:
The strcmp() and strncmp() functions return an integer less than,
equal to, or greater than zero if s1 (or the first n bytes thereof) is
found, respectively, to be less than, to match, or be greater than s2.
This would normally be implemented like #hroptatyr describes.
If you want to compare just the initial len characters of two strings, use strncmp instead of strcmp:
#include <string.h>
size_t len = 3;
int res = strncmp("dog", "dog2", len);
res will be 0 in this case.

Hidden or special characters in strings or different statement codes

How can I make my input string S1 of the fgets (or similar statement) to be equal to my declared static string S2?
#include <stdio.h>
#include <string.h>
main() {
char s1[80];
char s2[] = "This is a test.";
int l1, l2;
system("clear");
printf("%s\n\n", s2);
printf("Please type exactly the above sentence: ");
fgets(s1,80,stdin);
l1=strlen(s1);
l2=strlen(s2);
printf("\n String entered for S1, have a length of %d:\n %s", l1, s1);
printf("\n String static for S2, have a legnth of %d:\n %s", l2, s2);
if(s1==s2)
printf("\n\nOk! they're with the same length!\n");
else
printf("\n\nNop! They are NOT the same.\n");
return(0);
}
You're doing a pointer comparison, not a string comparison. To compare the content of the strings, use strcmp (docs):
if (strcmp(s1, s2) == 0)
...
fgets reads a line of input (up to a specified length, in your case 80). It stores that line in the array pointed to by its first argument (s1) -- including the terminating '\n' newline character.
Which means that after your fgets call, assuming you typed exactly "This is a test." and then typed Enter, s1 will contain "This is a test.\n", not just "This is a test.".
You can remove that newline character before the comparison -- or rather you can replace it with a null character '\0', which marks the end of the string:
size_t len = strlen(s1);
if (s1[len-1] == '\n') {
s1[len-1] = '\0';
}
(You might need to move the declaration of len to the top of main if your compiler doesn't support mixed declarations and statements -- but the strlen call still has to be done after fgets.)
To test whether the s1 and s2 contain the same string value, use the strcmp function; your s1 == s2 does a pointer comparison. strcmp returns 0 if the strings are equal. (If they're not, it returns a negative or positive value to indicate whether the left string is lexicographically less than or greater than the right string.)
Some minor comments on your code:
main() should be int main(void). (Long story; for now, just take my word for it.)
There's probably no need to invoke system("clear"). Why do you want to clear the screen? There might be useful information on it. And it won't work on all systems. If I want to clear my screen before running your program, I can do it myself, thank you very much.
Your message "they're with the same length" isn't quite right. If you correct the test by using strcmp rather than ==, you're testing whether the strings have the same value, whether their lengths happen to be the same or not.
Usually when you print a message, it's best to put the newline \n at the end of the output. It's usually best to have just a single \n at the end of the message (unless you want to print multiple lines with one printf, or build up one line with multiple printfs, which you can do but it's not necessary here.)
Your question originally had gets and scanf tags. Never use the gets function; it's inherently unsafe and has been removed from the language. scanf is tricky, and not needed in this case.

Begginger, string in switch in C with sourcecode. Possible?

So basically I wanted to create a program in C, in wich you would input 2 character long string (mix of letter and noumber ex.r1,u2,i3,i4,r6) to be the input in my program. Later I want to put this string in SWITCH. Is this possible?
Here's my simple sourcecode. Please correct me on any mistakes :)
#include <stdio.h>
int main(void)
{
char string[2];
scanf("%s", &string);
switch (string)
{
case 'u1' :printf("%s\n", string);break;
default :printf("ERROR");break;
}
return 0;
}
Create a code based on the string and switch on that.
#define Code(a,b) (a + 256*b)
char string[3]; // 3 not 2
if (scanf("%2s", string) != 1) { // No &
Handle_Error();
}
int scode = Code(string[0], string[1]);
switch (scode) {
case Code('u', '1') : printf("%s\n", string); break;
case Code('r', '2') : printf("r2\n"); break;
...
default :printf("ERROR");break;
}
A switch(x) needs an integer value for x and string is an array. So the original approach will not work.
The program can use an integer based on the string for x and use the same method for generating the case values. Since there is only the first 2 char of the string are of interest, the int value is unique.
No, this is not possible. Switch only works with integral types in C (int, short, long, etc, as well as types defined with enum).
You can however use a simple if-else construct to get the same behavior:
if (strcmp(string, "ui" ) == 0) //test for string equality
{
printf("%s\n", string);
}
else
{
printf("ERROR")
}
We use strcmp instead of == because we are dealing pointers which almost certainly not compare equal even when the two strings have the same content.
strcmp(str1, str2) == 0 is the standard idoim in C for comparing two strings.
strcmp returns an integer representing how two strings compare to each other. 0 means they are equal, a negative number means that the first string is lexographically "less than" the second, and a positive number means that the first string is lexographically "greater than" the second. More info can be found here.
A switch won't work here.
You need to use an if/else if construct and strcmp to compare the strings.
Also, you need at least 3 characters in your input array so that it can hold the two input characters and the terminating null character.
Of course, such a small buffer can easily overflow.

Resources