Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

scanf doesn't recognize numbers correctly

I was trying to make a program that makes a triangle comprised of numbers that are imputted. For example, if I input a string 123 the output should be the following.

1
12
123

I tried to implement it with the following code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main()
{
    char s[501];
    scanf("%[^\n]", s);
    for (int i=0;s[i]!='\0';i++) {
        for (int j=1;j<=s[i];j++) {
            printf("%d", j);
        }
        printf("\n");
    }
    return 0;
}

However, the output was the following (the input was 123):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

12345...4849
12345...484950
12345...48495051

Any ideas? Thanks

>Solution :

The problem doesn’t lie in scanf(). In this loop:

for (int i=0;s[i]!='\0';i++) {

s[i] gets converted to decimal value of the ASCII character (there
are other systems too like EBCDIC but most likely you’re not using
it). You can see it in man ascii – 1 is 49, 2 is 50 and 3 is 51. You
need to convert this number to a number that’s the same as the string
value of the character:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main()
{
    char s[501];
    scanf("%[^\n]", s);
    for (int i=0;s[i]!='\0';i++) {
        for (int j=1;j<=s[i]-'0';j++) {
            printf("%d", j);
        }
        printf("\n");
    }
    return 0;
}

Output:

$ ./main
123
1
12
123

Also, you don’t need to include <string.h> and <stdlib.h> and the
correct prototype of main() should be int main(void).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading