byDavid360
byDavid360

Reputation: 66

Program that receives size of string and lets you create it letter by letter in C

Ive got this program which im stuck with in which I am trying to receive the size of a string and following it, telling the user to input the letter by letter. Here is my code.

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

int main(){
    int size;
    int i;
    char letter;
    printf("Your string's size is...?: ");
    scanf("%d", &size);
    char mystring[size] ;
    for (i=0; i<size; i++){
        printf("Write a letter: \n");
        scanf("%c", &letter);
        mystring[i] = letter;

    }
    printf("%s",mystring);

    system("PAUSE");
    return 0;
}

Thanks!

Upvotes: 1

Views: 39

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

Two things:

First, you need to terminate the string with a \0-character. Otherwise, printf will result in undefined behaviour.

Second, note that scanf("%c",..) will probably consume a new line left in the buffer when a user presses "enter" after having entered a number (i.e. the size).

Write:

char mystring[size+1] ;
for (i=0; i<size; i++){
    printf("Write a letter: \n");
    scanf("%c", &letter);
    if (i==0 && letter == '\n') {
       i--;
       continue;
    }
    mystring[i] = letter;
}
mystring[size] = '\0';

printf("%s",mystring);

Upvotes: 3

dbush
dbush

Reputation: 224387

Two problems here.

First, the %c format specifier to scanf will read any character, including a newline. You need to put a space before it to absorb any newlines in the input buffer:

scanf(" %c", &letter);

Second, you don't null-terminate the string, nor do you leave enough space in the array to store the null terminator. Make the array one element larger, and add the null byte at the end:

char mystring[size+1];
for (i=0; i<size; i++){
    ...
}
mystring[size] = 0;

Upvotes: 4

Related Questions