Mindtrip
Mindtrip

Reputation: 33

Printing arrays while determining number of characters

My intention is randoming number between 0 & 1000 and print how mamy characters the number have? Then print another number and adding its character number to the total of character number.Code below compiles and windows gives runtime error after running.Couldn't find the error in the code.What is my error?

int main()
{
    char str [1000];
    int i=0;
    int k,a=0;

    printf("Number \tTotal\n");
    for(k=0;k!=10;k++)
    {
        i=rand()%1000;
        str[k]=i;
        printf("%s",str[k]);
        a+=strlen(str);
        printf("%s \t%d\n",str[k],a);
          }       


    getch();

    return 0;




    }

Upvotes: 0

Views: 53

Answers (3)

user2591612
user2591612

Reputation:

%s should be %c since you are just printing a char. a+=strlen(str) adds the previous strlen together. While you are printing the current char along with the most recent length of str.

int j is also unused.

You are printing str[k] twice, so it "doubles" up the characters on the line. If you want to store a more reasonable result, then reduce your random number down to 100. Also, I would reset a to 0 after every iteration in your loop.

Example output with changes:

Sayi    Toplam
S       5
V       5
M       5
        5
]       5
#       6
V       7
\       10
1       10
        10

Upvotes: 0

user694733
user694733

Reputation: 16043

You need to convert number to string first.

i = rand() % 1000;
length = snprintf(str, 1000, "%d", i); // Convert integer to string
printf("%s", str); // Print current string
a += length; // Add length
printf("%s \t%d\n", str, a); // Print current string and length so far

Upvotes: 1

AShelly
AShelly

Reputation: 35520

You are storing i, a number between 0 an 9999 in str, a character string, then taking the length of that invalid string. If you want to count the digits in the random number, you need to convert it to a string first with sprintf(str,"%d",i).

Upvotes: 0

Related Questions