我有一个非常简单的实验任务要做,我需要做的就是打印出字符串中的字符两次,除非它是空格。
由于我似乎无法弄清楚的原因,“echoString”函数正在无限循环。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
char* rhyme1 = "Hey Diddle diddle the Cat and the fiddle";
char rhyme2[265];
strncpy (rhyme2, "The Cow Jumped Over The Moon", sizeof(rhyme2));
char wordList[8][100];
/*Q1: Length of the string rhyme?*/
printf("Length: %d", strlen(rhyme1) );
/*Q2: Print out each letter twice, except for the spaces*/
echoString(rhyme1);
}
void echoString ( char* pString ) {
while ( *pString != '\0' ) {
if ( !isspace( *pString ) ) {
printf("%s%s", *pString, *pString);
}
else {
printf("%s", *pString);
}
pString++;
}
}
我感觉这与我如何递增指针或 isspace 函数有关。
感谢您的宝贵时间。
编辑:将“/0”更改为“\0”。因为没有看到这一点而感到愚蠢。
最佳答案
\0
用于空终止字符,而不是/0
。将'/0'
更改为'\0'
。使用
%c
打印char
,而不是%s
,后者用于打印改为字符串
。将所有%s
更改为%c
。
关于字符指针和空间搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325778/