2014-10-12 56 views
-3

我有這個非常簡單的實驗室任務要做,我需要做的就是打印出字符串中的字符兩次,除非是空格。字符指針和空間搜索

由於我似乎無法弄清楚的原因,「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'。覺得沒有看到這一點愚蠢。

+1

空字符爲** '\ 0' **的改變了首發 – Joel 2014-10-12 13:46:33

+0

。我覺得很愚蠢。這並沒有解決它傷心。 – Shaun 2014-10-12 13:51:26

+0

聽你的編譯器,你可能會得到'strncpy','strlen'和'echoString'(所有不兼容)的隱式聲明警告,'gcc -std = c99 -pedantic -Wall'我得到了錯誤的警告所有'printf'調用的格式字符串和多字符常量的警告。 – mafso 2014-10-12 14:00:08

回答

1
  1. \0爲空終止字符,而不是/0。將'/0'更改爲'\0'

  2. 使用%c打印char,不%s,這是一個string代替。將所有%s更改爲%c

+0

謝謝了。我認爲我正在增加錯誤的觀點。 – Shaun 2014-10-12 14:07:25

0
while (*pString != '/0') 

是錯誤的,因爲\0是空字符不/0。所以它改成

while (*pString != '\0') { 

然後,

printf("%s%s", *pString, *pString); 

也是錯誤的,只要你想兩次,每次字符將其更改爲

printf("%c%c", *pString, *pString); 

執行相同的

printf("%s", *pString); 

所以,你的程序應該是這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> //for strlen 
#include <ctype.h> 

void echoString(char*); //function prototype 
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\n", strlen(rhyme1)); 

/*Q2: Print out each letter twice, except for the spaces*/ 
echoString(rhyme1); 
return 0; 
} 

void echoString (char* pString) { 

while (*pString != '\0') {     //\0 is NULL not /0 

    if (!isspace(*pString)) { 
     printf("%c%c", *pString, *pString); //%c for a character 
    } 
    else { 
     printf("%c", *pString);    //%c for a character 
    } 
    pString++; 
} 
}