简体   繁体   English

在 C 中将字符串添加到 Char 数组中

[英]Adding Strings into a Char Array in C

For some reason when I print the array above I get a weird output.出于某种原因,当我打印上面的数组时,我得到了一个奇怪的 output。 When I run this code through the WinSCP terminal it also crashes almost as if there was an endless loop.当我通过 WinSCP 终端运行这段代码时,它也几乎像死循环一样崩溃。 However, I am mainly looking to fix the print output.但是,我主要是想修复打印 output。 Input: Tom (enter) Jerry (enter) (enter to break) Output: .N=?tom jerry输入:汤姆(输入)杰里(输入)(输入打破)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;
}

The array char nameArr[100] is not initialized, hence it contains garbage.数组char nameArr[100]未初始化,因此它包含垃圾。 It could be for example that this garbage is: nameArr[0] = '.'例如,这个垃圾可能是: nameArr[0] = '.' nameArr[1] = 'N' nameArr[2] = ':' ... nameArr[1] = 'N' nameArr[2] = ':' ...

So, you should write: char nameArr[100] = {0};所以,你应该写: char nameArr[100] = {0}; to initialize it to 0's, or make it static static char nameArr[100];将其初始化为 0,或将其设为static char nameArr[100]; which will also initialize it to 0's.这也会将其初始化为 0。

The strcat function requires that the destination array already is a proper null-terminated string. strcat function 要求目标数组已经是正确的以空字符结尾的字符串。

Since you haven't initialize the array nameArr its contents is indeterminate and the first call to strcat will lead to undefined behavior .由于您还没有初始化数组nameArr它的内容是不确定的,第一次调用strcat将导致未定义的行为

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 .您还应该添加检查以确保您不会 go 超出数组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.在不相关的说明中,请记住fgets将换行符留在缓冲区中,除非您希望nameArr包含换行符,否则您需要将其删除。

This can be done using the strcspn function:这可以使用strcspn function 来完成:

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

And lastly you should really check if fgets succeeds or not.最后,您应该真正检查fgets是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM