I'm adding the following to my char[]
int index = 0;
char i = '5';
char q = '7';
char val = (i - '0') + (q - '0');
array[index] = val;
++index;
If I print out val once the value has been assigned it prints out the value as 2 (as it should). However, if I then print out my char array like so.. printf("%.*s\n",index,array); Nothing prints but empty space. Why is this happening?
You haven't added '0' back to the number you put into the array (nor have you added a NUL terminator), so it's being printed out as whatever character happens to have the value 12 in the character set (and possibly code page) you're using (followed by whatever other contents memory may contain up until the next byte that happens to contain a zero).
In the ASCII character set (and derivatives such as Unicode) character 12 is a Form Feed character. If you fed it to a printer that understood ASCII, it would probably eject that page so text after it was printed on the next page. On screen, however, there's usually not much meaning to give to it, so it'll typically show up as a blank (or possibly some special character like a smiley face or something).
Each ASCII character has an integer value. When printing a character, the underlaying system checks the value of char variable and prints the corresponding ASCII character. The value itself is not printed. See ASCII table for reference.
char var = '7'; // var's value is actually 55.
char other = 55; // This is same as '7'
When calculating the sum of two digit characters, in your case '5' and '7', you have to subtract character '0' from them to convert '5' and '7' to numbers 5 and 7.
char first = '5' - '0'; // Is actually 53 - 48 = 5
char second = '7' - '0'; // Is actually 55 - 48 = 7
char result = first + second; // 5 + 7 = 12
// When you print result, you will not see "12" printed. Instead you see a form feed special character.
char test = '5' + '7'; // 53 + 55 = 108, which is letter 'l'
You have to convert the value of char to string to print the actual value. You can convert with itoa().
char result = ('5' - '0') + ('7' - '0');
char buf[5];
memset(buf, 0, sizeof(buf));
itoa((int)result, buf, 10);
printf("%s\n", buf);
You are telling printf that it's a string, but values are not printable ASCII values.
Well, assuming you meant it prints out the value 12, that means you're trying to print character number 12 in the ASCII character set. That character (http://www.asciitable.com/) is a non-printable character.
(Same goes for character 2 also actually).
You are probably misunderstanding the value as a numeric value, and this value as a printable character.
For example, x has value 2:
char ch = 7 - 5;
... but ch is the non-printable character 2. If you want the value in ch to be printable, then you must add it again the value of '0'.
char ch = x + '0';
If the value goes beyond 9, then a more complex algorithm must be used, in order to convert a number to a string.
The format string "%.*s" requires two arguments. The first, an int, for the minimum width to print (which is index (zero) in your case) and the second, a char*, for the data itself.
Conclusion: the program is behaving correctly by printing zero characters.
Related
int k=5;
char* result = (char *)malloc(100 * sizeof(char));
result[count] = k;
Considering the above code, if I print the contents of result[count] it prints smiley symbols. I tried like below,but of no use.
result[count]=(char)k;
Can anyone help me?
I am percepting that malloc(100*sizeof(char)) will create 100 blocks each of size of character contiguously. Please correct me if I am wrong?
I'll disregard all the fluff about arrays and malloc as it is irrelevant to the problem you describe. You seem to essentially be asking "What will this code print:"
char c = 5;
printf("%c", c);
It will print the symbol 5 in your symbol table, most likely a non-printable character. When encountering non-printable characters, some implementations choose to print non-standard symbols, such as smileys.
If you want to print the number 5, you have to use a character literal:
char c = '5';
printf("%c", c);
or alternatively use poor style with "magic numbers":
char c = 53; // don't write code like this
printf("%c", c);
It is a problem of character representation. Let's begin by the opposite first. A char can be promoted to an int, but if you do you get the representation of the character (its code). Assuming you use ASCII:
char c = '5';
int i = c; // i is now 0x35 or 53 ASCII code for '5'
Your example is the opposite, 5 can be represented by a char, so result[count] = k is defined (even if you should have got a warning for possible truncation), but ASCII char for code 5 is control code ENQ and will be printed as ♣ on a windows system using code page 850 or 437.
A half portable (not specified, but is known to work on all common architectures) way to do the conversion (int) 5 -> (char) '5' is to remember that code '0' to '9' are consecutive (as are 'A' to 'Z' and 'a to 'z'), so I think that what you want is:
result[count] = '0' + k;
First, let's clean up your code a bit:
int k=5;
char* result = malloc(100);
result[count] = k;
sizeof(char) is always equal to 1 under any platform and you don't need to cast the return of malloc() in C.
This said, as long as your count variable contains a value between 0 and 99, you're not doing anything wrong. If you want to print the actual character '5', then you have to assign the ASCII value of that character (53), not just the number 5. Also, remember that if that array of chars has to be interpreted as a string, you need to terminate it with '\0':
int k=5, i;
char* result = malloc(100);
for (i=0; i<98; i++) {
result[i] = ' ';
}
result[98] = 53;
result[99] = '\0';
printf("%s\n", result);
The elements in the array you're trying to allocate are all the size of a char, 1 byte. An int is 4 bytes thus your issues. If you want to store ints in an array you could do:
int result[100];
Followed by storing the value, but honestly from the way your questioned is posed I don't know if that's actually what you're trying to do. Try rephrasing the post with what you're trying to accomplish.
Are you trying to store 5 as a character?
So I have an array of integers. I use a for loop to transfer the contents of the int array into the char array. The problem is when I output the values, the decimal %d outputs 0 and 1s but the %c outputs a smiley emotion.
int main()
{
int array[10] = {0,1,0,1,1,0,1,1,1,0,0};
char array2[10];
int i;
for(i=0;i<10;i++)
{
array2[i] = array[i];
printf("%c %d\n", array2[i],array2[i]);
}
}
The smiley faces are symbols for "ASCII" characters 1 and 2 in Microsoft codepage 437; and character 0 is invisible; thus your code performs as expected, but maybe not like you intended.
To fill the char array with the ASCII '0' and '1' characters, you can do
array2[i] = '0' + array[i];
Try this:
array2[i] = array[i] + '0';
This converts 0 or 1 to '0' or '1'
c conversion specifier prints a character. ASCII values (I assume you live in the ASCII world) 0 and 1 are non-printable in ASCII. The ASCII value for '0' and '1' characters are 0x30 and 0x31. The result of printing a non-printable is implementation dependent.
What do you think ASCII character 0 or 1 should look like? I'm going to guess that on your system it prints as a smiley face because it is normally unprintable.
Maybe print the character as hex instead so you can see the bits are set. eg :
printf("%x", ch & 0xff);
(from solution here : Printing hexadecimal characters in C )
If you want to print characters as ints, you just need to cast them.
printf("%d\n", (int)array2[i]);
I'm trying to add an int to a char array. My (broken) code is as follows,
string[i] = (char) number;
with i being some int index of the array and number is some integer number. Actually, while typing this out I noticed another problem that would occur if the number is more than one digit, so if you have some answer to that problem as well that would be fantastic!
Given the revised requirement to get digit '0' into string[i] if number == 0, and similarly for values of number between 1 and 9, then you need to add '0' to the number:
assert(number >= 0 && number <= 9);
string[i] = number + '0';
The converse transform is used to convert a digit character back to the corresponding number:
assert(isdigit(c));
int value = c - '0';
If you want to convert a single digit to a number character you can use
string[i] = (char) (number+'0');
Of course you should check if the int value is between 0 and 9. If you have arbitrary numbers and you want to convert them to a string, you should use snprintf, but of course, then you can't squeeze it in a char aynmore, because each char represents a single digit.
If you create the digit representation by doing it manually, you should not forget that a C string requires a \0 byte at the end.
You'll want to use sprintf().
sprintf(string,'%d',number);
I believe.
EDIT: to answer the second part of your question, you're casting an integer to a character, which only holds one digit, as it were. You'd want to put it in a char* or an array of chars.
use asprintf :
char *x;
int size = asprintf(&x, "%d", number);
free(x);
is better because you don't have to allocate memory. is done by asprintf
It is a very trivial question but I don't know why I am not getting the correct output. Here is what I am trying to do:
char sendBuffer[1000];
int count=0:
while(count<10)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
In the output, all buffer is printed correctly except the first index. I want 1,2,3 and so on to be printed at the start of the buffer but it does not work. Please Help
You need to convert that number into a character. A cheap way to do it is:
sendBuffer[0] = '0' + count;
is there anyway to display integers greater than 9
If you need that you'll want to shift to more elaborate schemes. For example, if you want to convert an integer 42 into the string "42" you can say:
#define ENOUGH ((CHAR_BIT * sizeof(int) - 1) / 3 + 2)
char str[ENOUGH];
snprint(str, sizeof str, "%d", 42);
Credit for ENOUGH goes to caf.
printf(%s,sendBuffer); should be printf("%s",sendBuffer);
Change
sendBuffer[0]=count;
to
sendBuffer[0]='0' + count;
i.e. convert the integer 0...9 to the characters '0' ... '9'
Also add a quote i.e. printf("%s",sendBuffer);
Quoted from the question:
In the output, all buffer is printed correctly except the first
index.i want 1,2,3 and so on to be printed at the start of the buffer
but it does not work. Please Help
I think her problem is that she does not get any output for the first line. That is because in the first iteration, count is 0, i.e. sendBuffer[0] is 0 which is the '\0' character. Hence the string is treated as empty.
You are trying to print the ascii characters corresponding to decimal values 0-9 which are non-printable characters. If you need to print decimal 0-9 then initialise count to 48 which is the ascii decimal code for '0' and change the condition in the while block to count < 58; 57 is the ascii deciaml code for '9'. See below:
char sendBuffer[1000];
int count=48:
while(count<58)
{
sendBuffer[0]=count;
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
printf(%s,sendBuffer);
count=count+1;
}
To convert an integer value to a char representation, add the value of the character '0':
sendBuffer[0]=count + '0';
Notice that's the character '0', not the number 0. This is because of how ascii values work. The char with a literal value of 0 is \0, the null terminator. Digit '0' has a literal value of 48, '1' 49 and so on.
This works for the digits 0-9. You can't put a char representation of a number bigger than that in a single char, obviously.
char sendBuffer[1000];
// take fixed stuff outside the loop
sendBuffer[1]='a';
sendBuffer[2]='b';
sendBuffer[3]='c';
sendBuffer[4]='\0';
// it's best not to rely on order of ASCII values
for(char* numbers="0123456789"; *numbers!=0; numbers++){// use for loop for numbers
sendBuffer[0] = *numbers;
printf("%s",sendBuffer);
}
I have been attacking atoi from several different angles trying to extract ints from a string 1 digit at a time.
Problem 1 - Sizing the array
Should this array of 50 chars be of size 50 or 51 (to account for null terminator)?
char fiftyNumbersOne[51] = "37107287533902102798797998220837590246510135740250";
Problem 2 - atoi output
What am I doing wrong here?
char fiftyNumbersOne[51] = "37107287533902102798797998220837590246510135740250";
int one = 0;
char aChar = fiftyNumbersOne[48];
printf("%c\n",aChar);//outputs 5 (second to last #)
one = atoi(&aChar);
printf("%d\n",one);//outputs what appears to be INT_MAX...I want 5
Problem 1
The array should be length 51. But you can avoid having to manually figure that out by simply doing char fiftyNumbersOne[] = "blahblahblah";.
Problem 2
aChar is not a pointer to the original string; it's just an isolated char floating about in memory somewhere. But atoi(&aChar) is treating it as if it were a pointer to a null-terminated string. It's simply walking through memory until it happens to find a 0 somewhere, and then interpreting everything it's found as a string.
You probably want:
one = aChar - '0';
This relies on the fact that the character values for 0 to 9 are guaranteed to be contiguous.
51.
That's because aChar is not null-terminated. If you just want to get the integer value of a char, simply use
one = aChar - '0';
Problem 1 - Sizing the array Should
this array of 50 chars be of size 50
or 51 (to account for null
terminator)?
You always want an array one bigger than what you need to store in it (to account for the null terminator). So your 50 chars should be stored in an array of size 51.
What am I doing wrong here?
Try null terminating your input string to atoi. Documentation says atoi is supposed to be given the pointer to a string - which is different than a non-terminated single character. Your results with the current code you posted vary on different platforms (I get -1 on unbuntu/gcc) .
char fiftyNumbersOne[51] = "37107287533902102798797998220837590246510135740250";
int one = 0;
char aChar = fiftyNumbersOne[48];
char intChar[2];
printf("%c\n",aChar);//outputs 5 (second to last #)
sprintf(intChar, "%c", aChar); //print the char to a null terminated string
one = atoi(&intChar);
printf("%d\n",one);//outputs what appears to be INT_MAX...I want 5
Should this array of 50 chars be of size 50 or 51 (to account for null terminator)?
51, but you can also declare it without size.
char foo[] = "foo";
What am I doing wrong here?
Not reading the documentation for atoi I guess. aChar is a char, so you're passing the right type to atoi, but atoi is expecting this type to represent a string of characters, normally terminated by the character '\0'. Your "string" isn't terminated.
One solution to this is
char aString[2];
aString[0] = fiftyNumbersOne[48];
aString[1] = '\0';
atoi(aString);
Another is doing fiftyNumbersOne[48] - '0' instead of calling atoi, since in ASCII the decimal codes are consecutive and increasing from 0 to 9.