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);
}
Related
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
I want to make a program which converts 3www2as3com0 to www.as.com but I have got trouble at the beginning; I want to convert the first number of the string (the character 3) to an integer to use functions like strncpy or strchr so when I print the int converted the program shows 51 instead of 3. What is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
/* argv[1]--->3www2as3com0*/
char *string;
char *p;
string=argv[1];
p=string;
char cond,cond2;
cond=*p; //I want to have in cond the number 3
cond2=(int)cond; //I want to convert cond (a char) to cond2(an int)
printf("%d",cond2); //It print me 51 instead of 3
return (EXIT_SUCCESS);
}
Your computer evidently encodes strings in a scheme called ASCII . (I am fairly sure most modern computers use ASCII or a superset such as UTF-8 for char* strings).
Notice how both printable and nonprintable characters are encoded as numbers. 51 is the number for the character '3'.
One of the nice features of ASCII is that all the digits have increasing codes starting from '0'.
This allows one to get the numerical value of a digit by calculating aDigitCharacter - '0'.
For example: cond2 = cond - '0';
EDIT:
You should also probably also double check that the character is indeed a digit by making sure it lies between '0' and '9';
If you want to convert a string containing more than one digit to a number you might want to use atoi.
It can be found in <stdlib.h>.
The character's integer value is the ASCII code for the digit, not the number it actually represents. You can convert by subtracting '0'.
if( c >= '0' && c <= '9' ) val = c - '0';
Seems like the strings you are using will never have negative number, so you can use atoi(), returns the integer value from char. If it encounters something that is not a number, it will get the number that builds up until then.
While writing a program i am filling the entries of a char array with digits. After doing so the length calculated for an array having no zero is correct but for an array starting with zero is zero!
Why is this result coming so!I am not able to interpret my mistake!?
int main()
{
int number_of_terms,no,j,i;
char arr[100];
char c;
scanf("%d",&number_of_terms);
for(i=0;i<number_of_terms;i++)
{
j=0;
while(c!='\n')
{
scanf("%d",&arr[j]);
if(c=getchar()=='\n')
break;
j++;
}
printf("Length is:%d\n",strlen(arr));
}
return 0;
}
for eg if i input my array elements as 4 5
lenght is 2
and if my array elements as 0 5
length is 0..
You are using "%d" in your format specifier, which produces an integer, and you are passing in the address of a character array. This is, exactly like your title says, undefined behaviour. In particular, the value zero will take up 4 of the cells in your string, and will write zero to all of those. Since the character with value zero is the end marker, you get zero length string. However, on another architecture, the second character would probably cause a crash...
If you want to store integers in an array, you should use int arr[...];. If you want to store characters, use "%c".
You are copying the value 0 into the array. This eqals the character '\0' which is used to terminate strings. What you want is to copy the character '0' (has the value 48, see an ascii table).
Change %d to %c to interpret the input has character instead of decimal.
scanf("%c",&arr[j]);
Also your "string" in arr is not zero terminated. After all the characters of your string, you have to end the string with the value 0 (here a decimal is correct). strlen needs it, because it determines the length of the string by traversing the array and counting up until it finds a 0.
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.