user15448443
user15448443

Reputation:

Adding Strings into a Char Array in C

For some reason when I print the array above I get a weird output. When I run this code through the WinSCP terminal it also crashes almost as if there was an endless loop. However, I am mainly looking to fix the print output. Input: Tom (enter) Jerry (enter) (enter to break) Output: .N=?tom jerry

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    int i, counter = 0;
    char nameArr[100] ;
    
    while (1)
    {
        printf("Enter a name: ") ;
        char word[25] ;
        // Grab input
        fgets (word, sizeof(word), stdin) ;
        
        // Break if no input
        if (strcmp (word, "\n") == 0)
            break ;
        
        // Checks if there is a number in the input
        for (i = 0 ; i < strlen(word) - 1 ; i++)
        {
            int isItADigit = isdigit(word[i]) ;
            if (isItADigit != 0)
            {
                printf("No no, number detected, no bueno!") ;
                return 0 ;
            }
        }
        // Adds word to array
        strcat(nameArr, word) ;
        // Future Usage
        counter ++ ;    
    }
    
    if (counter < 2 )
    {
        printf("Name is too short\n") ;
        return 0 ;
    }
    else if (counter > 4)
    {
        printf("Name is too long\n") ;
        return 0 ;
    }
    
    //printArray(nameArr) ;
    printf("%s", nameArr) ;
    
    return 0;
}

Upvotes: 0

Views: 171

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409356

The strcat function requires that the destination array already is a proper null-terminated string.

Since you haven't initialize the array nameArr its contents is indeterminate and the first call to strcat will lead to undefined behavior.

You need to initialize the array before you use it:

char nameArr[100] = { 0 };  // Initialize to all zeros, which is the string terminator

You should also add a check to make sure that you don't go out of bounds of the array nameArr.


On an unrelated note, remember that fgets leaves the newline in the buffer, and you need to remove it unless you want your nameArr to contain newlines.

This can be done using the strcspn function:

fgets (word, sizeof(word), stdin) ;
word[strcspn(word, "\n")] = '\0';

And lastly you should really check if fgets succeeds or not.

Upvotes: 1

Orielno
Orielno

Reputation: 409

The array char nameArr[100] is not initialized, hence it contains garbage. It could be for example that this garbage is: nameArr[0] = '.' nameArr[1] = 'N' nameArr[2] = ':' ...

So, you should write: char nameArr[100] = {0}; to initialize it to 0's, or make it static static char nameArr[100]; which will also initialize it to 0's.

Upvotes: 2

Related Questions