Home > OS >  C printing ASCII symbols
C printing ASCII symbols

Time:08-24

I'm trying to fetch individual characters from user input for a char array, print the input as a string, and then print every individual element as they were entered. Here is my code:

#include <stdio.h>

int main(void)
{
    char string[9];

    int i;
    int counter1 = 0;
    int counter2 = 0;

    for (i=0; i<=10; i  )
    {
        printf("Enter character for element %d: ", counter1);
        scanf("%c\n", &string[counter1]);
        counter1  ;
    }
    printf("Your input: %s", string);
    printf("\nArray values:\n");

    while (counter2<=9)
    {
        printf("Element %d: %c\n", counter2, string[counter2]);
        counter2  ;
    }
}

Here is the output:

Enter character for element 0: w
w
Enter character for element 1: w
Enter character for element 2: w
Enter character for element 3: w
Enter character for element 4: w
Enter character for element 5: w
Enter character for element 6: w
Enter character for element 7: w
Enter character for element 8: w
Enter character for element 9: w
Enter character for element 10: w
Your input: wwwwwwwwwww�tI�(�)���Array values:
Element 0: w
Element 1: w
Element 2: w
Element 3: w
Element 4: w
Element 5: w
Element 6: w
Element 7: w
Element 8: w
Element 9: w

CodePudding user response:

You're using both 9 and 10 and hoping it will all work out.

#include <stdio.h>

#define LEN 10 // Clearly visible dimension

int main( void ) {
    char string[ LEN   1 ]; // Show you know about the required '\0'

    int i;
    int counter1 = 0;

    for( i = 0; i < LEN; i   ) {
        printf("Enter character # %d: ", i );
        scanf( "%c", &string[ i ] ); // holding my nose...
        counter1  ;
    }

    string[ i ] = '\0'; // transform char array into "C-style string"

    printf( "Your input: '%s'\n\n", string ); // apostrophes to highlight string

    printf("\nArray values:\n");
    for( i = 0; i < counter1; i   ) { // Notice upper limit of loop?
        printf( "Element %d: %c\n", i, string[ i ] );
    }
}

CodePudding user response:

the char array string has size 9 and you should make it bigger (some thing like 20 or more).

  •  Tags:  
  • c
  • Related