This question already has answers here:
How do I determine the number of digits of an integer in C?
(20 answers)
Closed 8 years ago.
The program below is sufficent enouhgh to find the length of any string length that is given to the input, however, i need to find the length of an integer variable, rather than a string.
Entering a number to this does work, but not if i scan s as a int type.
int main()
{
char s[1000];
char i;
int u=5;
do
{
char s[1000];
char i;
int u=5;
system("cls");
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
getch();
}
while(u==5);
getch();
}
So all i need is either this little program modified to accept intger variables, or a way to transform a calculated int variable into a string.
Any ideas?
Edit: Length = Amount of characters so 25 has 2, 3456 has 4 etc
Either use itoa to convert the integer to string and then use your code to calculate the length or
int i;
for (i=0; num!=0; i++, num=num/10){}
should give you the length of the number in i.
I guess the above example should work fine for integers also. Say if my string is 12345 then I will get 5 as my answer.
However, what else you can do is, input an integer, say i and then do the following.
while(i!=0){
length++;
i = i/10;
}
Here, I am considering i is an integer variable and not a character array.
You can use log10 and ceil functions from math.h instead.
int length = (int)(number ? log10(number) + 1 : 1);
Related
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 2 years ago.
Improve this question
I am a beginner to c language. Please help me to find the error of the code as it gives a complilation error on the display.
#include <stdio.h>
#include <string.h>
void main()
{
char i;
char arr[23];
printf("Enter your name? \n");`
scanf("%c",&arr[i]);
for(int v=0;v<=strlen(arr);v++)
{
printf("%c",arr[v]);
}
}
Your code has several issues, not only one:
1.
You use the wrong format specifier %c to catch a single character instead of %s to catch a string:
char arr[23];
printf("Enter your name: \n");`
scanf("%c",&arr[i]);
Rather use scanf("%s",arr); or even better scanf("%Ns",arr); where N stands for the maximum number of characters to be entered. Note that you need one element for the string-terminating null character, so it requires to be at least one character less than the char array is consisted of.
You can also use fgets(arr,23,stdin) which is preferred for consuming strings from the standard input because it is more safe as it requires you to provide the maximum amount of characters to read (counting the null character too) and also reads white space separated words as part of the string by default.
2.
i is not initialized to any value, so:
scanf("%c",&arr[i]);
causes undefined behavior.
3.
Furthermore you try to get a string length by using strlen() as part of the condition expression of the for loop:
for(int v = 0; v <= strlen(arr); v++)
although there is no valid string in arr which causes also undefined behavior.
As a side note here: It is more efficient to use strlen() only once before the for loop, store its return value in an object of an appropriate type (size_t is the type of the return value of strlen()) and use that object in the condition of the for loop instead of executing strlen() before each iteration.
4.
Next thing is that you attempt to print characters inside the for loop which aren´t provided/initialized to arr:
for(int v = 0; v <= strlen(arr); v++)
{
printf("%c",arr[v]);
}
5.
The for loop with the condition v <= strlen():
for(int v = 0; v <= strlen(arr); v++)
runs one time more than expected and prints the null character which is redundant since the null character is not printable.
Rather use v < strlen() or according to point 3:
size_t len = strlen(arr);
for(int v = 0; v < len; v++)
6.
The return value of main shall be int, not void.
7.
There is a trailing apostrophe after the printf() call:
printf("Enter your name: \n");`
Rather use:
#include <stdio.h>
int main()
{
char arr[23];
printf("Enter your name: \n");
scanf("%22s",arr);
printf("%s",arr);
}
Online Example
if you want to print out the string entered as whole at once, or:
#include <stdio.h>
#include <string.h>
int main()
{
char arr[23];
printf("Enter your name: \n");
scanf("%22s",arr);
size_t len = strlen(arr);
for(int v = 0; v < len; v++)
{
printf("%c",arr[v]);
}
}
Online example
if you want to print each character separate.
Your error is not really an error. You have an extra character in this lane:
printf("Enter your name? \n");`
It should be:
printf("Enter your name? \n");
There is a ` at end of the line
printf("Enter your name? \n");`
note you are using uninitialized int i here scanf("%c",&arr[i]); which is wrong.
also with scanf("%c",&arr[i]); you can only scan one character for string arr which I think is not your purpose.
you can use scanf("%s",arr[i]); instead to appropriately scan an string .
also note when ever you are scanning string char by char you have to add terminator \0 to the end of your string.after scanning characters until element i-1 of array add \0 to element i like this arr[i]=\0;.
since your string isn't terminated appropriately strlen won't work well.
also note you should print elements of string while v<strlen(arr) the last char should be \0 so you should use in for(int v=0;v<=strlen(arr);v++)
also pay attention to use int main not void main.
look:
void main()
{
char arr[23];
printf("Enter your name? \n");
scanf("%s",arr);
for(int v=0;v<strlen(arr);v++)
{
printf("%c",arr[v]);
}//or instead of loop use printf("%s",arr);
}
I am new to C programming and trying to make a program to add up the digits from the input like this:
input = 12345 <= 5 digit
output = 15 <= add up digit
I try to convert the char index to int but it dosent seems to work! Can anyone help?
Here's my code:
#include <stdio.h>
#include <string.h>
int main(){
char nilai[5];
int j,length,nilai_asli=0,i;
printf("nilai: ");
scanf("%s",&nilai);
length = strlen(nilai);
for(i=0; i<length; i++){
int nilai1 = nilai[i];
printf("%d",nilai1);
}
}
Output:
nilai: 12345
4950515253
You have two problems with the code you show.
First lets talk about the problem you ask about... You display the encoded character value. All characters in C are encoded in one way or another. The most common encoding scheme is called ASCII where the digits are encoded with '0' starting at 48 up to '9' at 57.
Using this knowledge it should be quite easy to figure out a way to convert a digit character to the integer value of the digit: Subtract the character '0'. As in
int nilai1 = nilai[i] - '0'; // "Convert" digit character to its integer value
Now for the second problem: Strings in C are really called null-terminated byte strings. That null-terminated bit is quite important, and all strings functions (like strlen) will look for that to know when the string ends.
When you input five character for the scanf call, the scanf function will write the null-terminator on the sixth position in the five-element array. That is out of bounds and leads to undefined behavior.
You can solve this by either making the array longer, or by telling scanf not to write more characters into the array than it can actually fit:
scanf("%4s", nilai); // Read at most four characters
// which will fit with the terminator in a five-element array
First of all, your buffer isn't big enough. String input is null-terminated, so if you want to read in your output 12345 of 5 numbers, you need a buffer of at least 6 chars:
char nilai[6];
And if your input is bigger than 5 chars, then your buffer has to be bigger, too.
But the problem with adding up the digits is that you're not actually adding up anything. You're just assigning to int nilai1 over and over and discarding the result. Instead, put int nilai1 before the loop and increase it in the loop. Also, to convert from a char to the int it represents, subtract '0'. All in all this part should look like this:
int nilai1 = 0;
for (i = 0; i < length; i++) {
nilai1 += nilai[i] - '0';
}
printf("%d\n", nilai1);
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
This character array
char nilai[5];
can not contain a string with 5 digits. Declare the array with at least one more character to store the terminating zero of a string.
char nilai[6];
In the call of scanf
scanf("%s",&nilai);
remove the operator & before the name nilai. And such a call is unsafe. You could use for example the standard function fgets.
This call
length = strlen(nilai);
is redundant and moreover the variable length should be declared having the type size_t.
This loop
for(i=0; i<length; i++){
int nilai1 = nilai[i];
printf("%d",nilai1);
}
entirely does not make sense.
The program can look the following way
#include <stdio.h>
#include <ctype.h>
int main(void)
{
enum { N = 6 };
char nilai[N];
printf( "nilai: ");
fgets( nilai, sizeof( nilai ), stdin );
int nilai1 = 0;
for ( const char *p = nilai; *p != '\0'; ++p )
{
if ( isdigit( ( unsigned char ) *p ) ) nilai1 += *p - '0';
}
printf( "%d\n", nilai1 );
return 0;
}
Its output might look like
nilai: 12345
15
I am writing a program that takes an integer and then makes array of arrays of char and finds the number of every occurrence of every char in all lines. This two dimensional array has the size of "lineNumber". The code is shown below.
The problem is when i get an input more than 3 digits, it stops working and exits. I really found that the problem is with declaring the array of array of chars. Can you tell me how to overcome this problem? For example i want to take an input of 1000 line?
The problem is not with the scanf function, i know that. Can you fix my code?
printf("Number of lines: ");
int lineNumber;
int n = scanf("%d", &lineNumber);
if (n == 0) {
puts("Use integers.");
return n;
}
char lines[lineNumber][1024]; /* It can't declare more than 3 digit integer */
int i = 0;
for (;i < lineNumber; i++) {
printf("%d: ", i+1);
fgets(lines[i], 1024, stdin);
lines[i][strlen(lines[i])-1] = '\0';
}
/* count the number of occurrence of every char in all lines */
If lineNumber is for example 9000:
char lineptr[lineNumber][1024];
then lineptr uses about 9000*1024 = 9MB of stack space. Depending on your os and system configuration, this might be too much crashing your program. Stack space is usually limited.
If you need a big amount of space, better allocate the memory with malloc().
I have question about scanf a string. I am completing a practice exercise on encoding a Vigenere cipher.
It is easy to solve it at other language but in C I have trouble and I don't know why it is.
This is my code.
#include<stdio.h>
#include<string.h>
main()
{
char mes[1000];
char key[100];
int n=strlen(mes);
int cipher[n],i,j=0;
printf("Enter message \n");
scanf("%s",mes);
printf("Enter keyword \n");
scanf("%s",key);
printf("len message= %d \n",strlen(mes));
for(i=0;i<strlen(mes);++i)
{
mes[i]=toupper(mes[i]);
key[j]=toupper(key[j]);
if(j==strlen(key))
j=0;
cipher[i]=((mes[i]-0x41)+(key[j]-0x41)) % 26;
printf("%c",cipher[i]+0x41);
++j;}
printf("\n");
}
My code work well if mes array input is less than 16 character, but if mes input larger the program loop infinite. I don't know why.
If I change type of cipher array to char type, it seem work better, but the result still have wrong output like this:
Enter message
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Enter keyword
eeeeeeeeeeeeeeeeeee
len of message= 45
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE�EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEEEEE
So can you explain:
1) Why my code do wrong if cipher array is an int type?
2) If cipher is char, the output better but why It have wrong output?
Couple of problems:
Allocating memory for cipher doesn't work properly
int n=strlen(mes); // mes has nothing now..so n=0!
int cipher[n],i,j=0;
Rolling back j should be done after increment .
Put this piece after you read both inputs..it should work for any length<100
int cipher[strlen(mes)];
for(i=0;i<strlen(mes);++i)
{
mes[i]=toupper(mes[i]);
key[j]=toupper(key[j]);
cipher[i]=((mes[i]-'A')+(key[j]-'A')) % 26; //use 'A' for better readability
printf("%c",cipher[i]+'A');
++j;
if(j==strlen(key))
j=0;
}
In simple words, You wrote int n=strlen(mes); before giving any input,Now how would you determine the size of input when its still not given,See my comments in below code,
char mes[1000];
char key[100];
int n,i,j=0;
printf("Enter message \n");
scanf("%s",mes);
n=strlen(mes);//Determining Size of Input after giving it.....
int cipher[n];//Add This Here,Now You Create a array after Determining input size.
printf("Enter keyword \n");
scanf("%s",key);
printf("len message= %d \n",strlen(mes),strlen(key));
You didn't initiate the length of the chiper array correctly.. In your code:
char mes[1000];
char key[100];
int n=strlen(mes);
int cipher[n];
The length of chiper array here is undefined..
Unless you write something like:
int chiper[1000];
BR//Ari
This question already has answers here:
Converting int to string in C
(14 answers)
Closed 8 years ago.
You read the question I need to be able to scan a int value and print it back out as a string variable
If you just want to print it back, you can use the "%d" specifier when using printf. If you want to convert the integer value to a character string for other purposes, you can use itoa.
YOu should use sprintf instead of itoa as it iota is not a starndard
int aInt;
scanf("%d", &aInt)
char str[50];
sprintf(str, "%d", aInt);
detail use of sprintf
You can use the sprintf function to do it.
int a;
// [log(2^63 - 1)] + 1 = 19 where
// [x] is the greatest integer <= x
// +1 for the terminating null byte
char s[19+1];
// read an integer
scanf("%d", &a);
// store the integer value as a string in s
sprintf(s, "%d", a);