【发布时间】:2021-03-26 20:51:16
【问题描述】:
由于某种原因,当我打印上面的数组时,我得到了一个奇怪的输出。当我通过 WinSCP 终端运行这段代码时,它也几乎像死循环一样崩溃。但是,我主要是想修复打印输出。输入:Tom (enter) Jerry (enter) (enter to break) 输出:.N=?tom 杰瑞
#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;
}
【问题讨论】:
-
你必须以'\0'结束一个字符串。或者程序不知道字符串在哪里结束。
标签: arrays c loops fgets strcat