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 want two create two functions that can do this. So one function takes a character, for example the character a and returns the integer 97. The other function takes this integer 97 and returns the character a. I know this can be done by using the ASCII codes of these characters, but then it wouldn't work for characters like é, à, ö. Can this be done using unicode or another way?
For example:
int character_to_integer(char c) {
convert character to integer and return
}
Input: character_to_index('é');
Output: 102 (for example)
char integer_to_character(int i) {
convert integer to character and return
}
Input: integer_to_character(102);
Output: é
I want to do this with it: have an array, so for example int my_array[5] with all elements set to NULL at the start. Then for example, index 0, 3 and 4 (which correspond to a, d and e for example) are set to something other than NULL then I want to loop over it and build a string based off the which indexes aren't NULL, like so:
void build_string_from_array(int my_array) {
char buffer[16];
char c;
for (i = 0; i < 5; i++) {
if (my_array[i] != NULL) {
c = integer_to_character(i);
buffer[i] = c;
}
}
buffer[5] = '\0';
printf("%s\n", buffer);
}
Output: ade
Note, this is just an example, and I know there is probably something wrong with it, but it's just to get my point across. I know this can be done with ASCII codes, where all the characters are only 1 char, but how can this be done so that characters like é, that are seen as 2 chars would also work?
If it's not clear what I mean just ask me and I'll elaborate some more.
For single Byte chars, this is no Problem, since char is a integer:
int i = 'B';
and
char c = 0x33;
will work fine.
But, if you use UTF8 with chars with more than one Byte, you must convert the UTF8-String to a UCS4 String. Sadly there is no Standard API for that.
See also this Post: Converting a UTF-8 text to wchar_t
A other way is use wchar_t everywhere. This will not work well on Windows with chars outside the BMP, since the wchar_t implementation in Windows is brocken (wchar_t is still a Multibyte Character Set on Windows). On Linux it will work, if you not use compound chars.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
This code is to change decimal "n" to binary that I wrote like this:
#include<stdio.h>
#include<string.h>
int main(){
char str[] = "";
int a = 5;
int n = 5;
while(n > 0){
if (n % 2 == 0) {
strcat(str,"0");
} else {
strcat(str, "1");
}
n = n / 2;
}
strrev(str);
printf("%s", str);
return 0;
}
The problem here is, when I tried to debug and see the variable changing, the "a" changed in a very strange way, although I don't do anything to "a". Why is it like that?
The array str, because it doesn't have an explicit size, is sized to exactly store what it is initialized with. And because an empty string only contains 1 character, namely a terminating null byte, your array is 1 element in size.
This means str isn't large enough to hold any string that's not an empty string, so using strcat on it causes the function to write past the end of the array, triggering undefined behavior. In this case, it manifests as writing into another variable which happens to be adjacent to the array in memory.
The array must be sized properly to hold whatever string it might hold, i.e.:
char str[33] = "";
This gives you enough space to store the binary representation of any nonnegative 32 bit integer.
char str[] = "";
Since there's no explicit length given, the array is given the length of the "" initializer, which contains a single \0 character. This declaration is equivalent to:
char str[1] = {'\0'};
There is no space reserved for additional characters. When you do strcat(str,...) it writes past the end of the array and triggers undefined behavior.
You can fix this by allocating extra space:
char str[100] = "";
Or if you don't like an arbitrary 100 and want the exact size that can handle all numbers:
char str[sizeof n * CHAR_BIT + 1] = "";
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When I try to convert a char[] to char* there are unneeded characters added to the char* variable
int keySize = getKeySize(key2);
char* key = (char*)malloc(sizeof(keySize));
int i;
char s[keySize-1];
int i2;
for(i2=0; i2<keySize; i2++)
{
s[i2] = getCharacter(key2, i2);
}
strncpy(key, s, keySize);
There is no string data type in C programming language. Strings in C are represented as array of characters.
Note: C-Strings are actually character array terminated by '\0' character. That means, last character in any C-String in C will be used to store a '\0' character which marks the end of the string. To store n characters in C-String in C, you should define a character array of size (n+1).
Why should we terminated it by '\0'?
The '\0' termination is what differentiates a char array from a c-string in C programming language. Most string-manipulating functions (like strcpy) relies on '\0' character to know when the string is finished (and its job is done!), and won't work with simple char-array (eg. they'll keep on working past the boundaries of the array, and continue until it finds a '\0' character somewhere in memory - often corrupting memory as it goes).
Therefore, storing a '\0' character (at the end) is necessary if you want to use functions of #include <string.h> like strcpy() as they rely on '\0' character to mark the end of the character array.
'\0' is defined to be a null character - that is a character with all bits set to zero (and thus has a value 0). This has nothing to do with pointers. Read more about it here.
In your program, you want two character arrays key (dynamically allocated) and s to hold a copy of another character array key2 of size keysize. Then, both character arrays should be of atleast keysize + 1 (+1 to hold a '\0' character) size.
Change:
char* key = (char*)malloc(sizeof(keySize));
To:
char* key = malloc(keySize+1); // Don't Type-Cast malloc
And
Change:
char s[keySize-1];
To
char s[keySize+1];
While allocating, you should allocate one more than the size. Currently you are allocating 4 bytes only.
char* key = (char*)malloc(keySize+1);
//instead of
char* key = (char*)malloc(sizeof(keySize));
s should have a size of keySize+1
char s[keySize+1];
// instead of
char s[keySize-1];
What about this?
There are some errors about the dimension of s, I suggest you tu use strncpy
#include <string.h>
int main(){
//bla bla ...
int keySize = getKeySize(key2);
char* key = malloc(keySize+1);;
int i2;
for(i2=0; i2<keySize; i2++){
s[i2] = getCharacter(key2, i2);
}
char s[keySize+1];
strncpy(s, key, sizeof s - 1);
s[keySize] = '\0';
r
return 0;
}
Anyway more information about it please,I supposed you wanted this
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a string that looks like "AGE:83". I want to take the integer "83" out of this string, and I know that I should use the "sscanf" function. However, there is no white space between this string. How can I do that?
Use this:
const char *str = "AGE:83";
int age;
sscanf(str, "%*[^0-9]%d", &age);
This format will skip any non digits and parse an integer after that.
Note that it will fail if there are no non digit characters before the number. To handle the case where the number can be at the start of the string, use first try a direct match:
if (sscanf(str, "%d", &age) != 1
&& sscanf(str, "%*[^0-9]%d", &age) != 1) {
// no number found;
return 1;
}
// age was correctly extracted from `str`
Negative numbers cannot be parsed this way, unless you know the prefix does not contain a '-' (using format "%*[^0-9-]%d")
You can also use a string function to skip the prefix and convert the rest for atoi() or strtol():
age = atoi(str + strcspn(str, "0123456789"));
As noted by Enzo Ferber, if the format of the string is fixed and is known to start with AGE:, you can just convert the remainder of the string with:
age = atoi(str + 4);
But this would invoke undefined behavior if the string is shorter than 4 characters as you would be potentially dereferencing invalid addresses.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to set input value as decimal
int data = 2000;
and then, output as hexadecimal string or char format:
hexValue = 0x7D0;
then need to extract the value in following format:
char hexdata[]= {0x07, 0xD0};
How can this be achieved by writing a C program? I am using KEIL MDK-5 IDE. Any idea?
try following
int data=2000;
char hexdata[4];
printf("hexValue = %x", data);
hexdata[3] = data & 0xFF;
hexdata[2] = (data>>8) & 0xFF;
hexdata[1] = (data>>16) & 0xFF;
hexdata[0] = (data>>24) & 0xFF;
you can choose to write a for loop for extracting hexdata
Unfortunately, I couldn't understand what do you need really, If you want to represent one byte of a decimal value in hex format at a time, you can use the following code or something like that.
int main(void)
{
int a = 2000;
unsigned char *p = (unsigned char *)&a;
int i;
printf("a =");
for (i = 0; i < sizeof(a); ++i)
{
printf(" %02x", p[i]);
}
printf("\n");
return 0;
}
If this works for you.
int main(void)
{
int a = 2000;
char str[8];
int i;
sprintf(str, "%X", a);
// now you have the number as a character in str variable. you can seperate them using string functions now.
return 0;
}
Easiest way to do number system conversions is using strtol function. Of course, you need to:
Convert decimal number into string. Please, read more about that here: How to convert integer to string in C?
Use strol function to get hexadecimal value.
From man pages:
long int strtol(const char *nptr, char **endptr, int base);
long long int strtoll(const char *nptr, char **endptr, int base);
The strtol() function converts the initial part of the string in nptr to a
long integer value according to the given base, which must be between
2 and 36 inclusive, or be the special value 0.
The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional '+' or '-'
sign. If base is zero or 16, the string may then include a "0x"
prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0',
in which case it is taken as 8 (octal).
The remainder of the string is converted to a long int value in the obvious manner, stopping at the first character which is not a
valid digit in the given base. (In bases above 10, the letter 'A'
in either uppercase or lowercase represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.)
If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all,
strtol() stores the original value of nptr in *endptr (and returns 0).
In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.
The strtoll() function works just like the strtol() function but returns a long long integer value.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I'm trying to write a C program that counts the number of words and spaces in a given string. Here's what I have so far:
#include <stdio.h>
int main()
{
int i, spaces;
char a[30];
printf("enter the string");
scanf("%s", a);
for(i=0 ; a[0]!="\0" ; i++
{
if (a[i]=' ')
{
spaces++;
}
}
printf("Number of spaces is %d", spaces);
printf("Number of words is %d", spaces + 1);
}
It gives me a weird error at 9:19. Help would be much appreciated.
Updated:
#include <stdio.h>
int main()
{
int i,spaces;
char a[100];
printf("enter the string\n");
scanf("%s",a);
for(i=0 ; a[i]!='\0' ; i++)
{
if (a[i]==' ')
{
spaces++;
}
}
printf("the no. of spaces in the string is %d\n",spaces);
printf("the no. of words in the string is %d\n",spaces+1);
}
Now doesn't metter what string I input, it'll say there's 0 spaces and 1 word. Why is this?
The first think, you forgot the for closing parenthese. And the condition expression you must use '\0' instead of "\0". Also you need to check a[i] not a[0].
for(i = 0; a[i] != '\0'; i++)
{
if (a[i] == ' ')
{
spaces++;
}
}
Note that you should initialize spaces to 0 before using it.
spaces = 0;
Update:
Another thing, to input a full string with spaces use fgets() instead of scanf:
fgets(a, 100, stdin);
The first argument is your string, the second is the maximum number of characters to input and the third is the stream from where you will get the input: stdin in your case wich is the standard input stream.
Live exemple: https://eval.in/101504
In C, a char[] literal is written with double quotes ("), and a char literal is written with single quotes ('). Change "\0" to '\0'. This is the source of your "weird error."
The bracket syntax is syntactic sugar for dereferencing an offset pointer to a contiguous block of memory, based on what you declared it would contain. Maybe a crude diagram could help? This is a depiction of a char[5]. It's a pointer block of memory that can hold 5 chars and a null terminator.
['h']['e']['l']['l']['o']['\0']
^
a // you called your char[] a, so I did too
A char* is a pointer to a char. So you could also call a a char*. Say you wanted to access the first 'l' in the char[]... well, you'd have to point to the address exactly 2*sizeof(char) ahead. a[2] is the same thing as *(a+(2*sizeof(char))).
So when you dereferenced your char* you got a char, obviously. But "\0" is a char[] literal (i.e. a string) and you can't compare the two.
Other problems: you should close the parentheses on your for loop, and make your comparison a[i]!='\0' (that way you are checking each char as you iterate through the char[]. I think you also meant to check if(a[i]==' '). Otherwise you will be clearing out your string with spaces :)
A little tip for going forward: if you are comparing a variable to a literal, put the literal first so you're less likely to make typos like that. e.g. ' '==a[i]. If you used = instead you would get an error (because you'd be trying to assign something to a literal).
Edit: since you updated your code, I'd like to point out that you should probably initialize spaces to be 0.
Now I won't take credit for this, but in case someone in the future is reading, fgets is what you're looking to use instead of scanf. Thanks to drch for pointing this out.
You're always comparing a[0] to '\0' so your loop continues endlessly, compare it to a[i].
One more thing is that "\0" is a string (char*), you need to compare it to '\0' which is a char.
The reason you're getting 0 and 1 is because of the way you're using scanf. Using scanf with %s just reads the first string that does not include white space. So if you typed
"The fox jumped over the moon"
The output will be 0 spaces and 1 word. This is because scanf(%s, a) will just put "The" into a and will ignore the rest of the string.
http://www.cplusplus.com/reference/cstdio/scanf/
You can use scanf("[^\r\n]", a). I believe that should get you what you want (or close to it anyway).