[英]Adding Strings into a Char Array in C
出於某種原因,當我打印上面的數組時,我得到了一個奇怪的 output。 當我通過 WinSCP 終端運行這段代碼時,它也幾乎像死循環一樣崩潰。 但是,我主要是想修復打印 output。 輸入:湯姆(輸入)傑里(輸入)(輸入打破)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;
}
數組char nameArr[100]
未初始化,因此它包含垃圾。 例如,這個垃圾可能是: nameArr[0] = '.'
nameArr[1] = 'N'
nameArr[2] = ':'
...
所以,你應該寫: char nameArr[100] = {0};
將其初始化為 0,或將其設為static char nameArr[100];
這也會將其初始化為 0。
strcat
function 要求目標數組已經是正確的以空字符結尾的字符串。
由於您還沒有初始化數組nameArr
它的內容是不確定的,第一次調用strcat
將導致未定義的行為。
您需要在使用數組之前對其進行初始化:
char nameArr[100] = { 0 }; // Initialize to all zeros, which is the string terminator
您還應該添加檢查以確保您不會 go 超出數組nameArr
的范圍。
在不相關的說明中,請記住fgets
將換行符留在緩沖區中,除非您希望nameArr
包含換行符,否則您需要將其刪除。
這可以使用strcspn
function 來完成:
fgets (word, sizeof(word), stdin) ;
word[strcspn(word, "\n")] = '\0';
最后,您應該真正檢查fgets
是否成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.