2017-09-14 26 views
0

幫助!我用C編寫一個程序來獲取所有的英文縮寫 - 我一無所知指針所以讓我們嘗試從那些遠離 - 這是我到目前爲止有:從字符串(名稱)中獲取首字母的程序,無法刪除所有空格

#include <stdio.h> 
//CS50 Library for 'get_string() user input' 
#include <cs50.h> 
#include <string.h> 
#include <ctype.h> 

int main(void){ 
    printf("Enter your name: "); 
    //User input for string 
    string s = get_string(); 
    int i = 0; 
    //Determine whether the first chars are space - if not print char 
    if(s[0] != isspace(s[0])){ 
      printf("%c",s[0]); 
     } 
    //loop through each Char - determine char is not space 
    while(s[i] != '\0'){ 
     if(s[i] == ' '){ 
      //if i'th char is space - add one to it thus printing char that comes after space 
      printf("%c", toupper(s[i+1])); 
     } 
     //advance i'th char count 
     i++; 
    } 
    printf("\n"); 
} 

當我輸入「約翰·傑拉爾德·史密斯」該程序會返回「JGB」,但如果我嘗試輸入諸如「John gerald smith」(多個空格)之類的字詞,它似乎不會刪除任何空格。我仍然得到輸出的首字母,但我需要確保它不會打印任何空格。請幫忙!這是家庭作業,所以我不希望只是交出答案,但如果任何人都可以給我一些關於如何做的信息,我會非常感激。謝謝!

+0

不要只是看當前字符,而且NEXT字符是否不是空格。小心邊界檢查(不要超過字符串的末尾!) – meisen99

回答

0
#include <stdio.h> 
//CS50 Library for 'get_string() user input' 
#include <cs50.h> 
#include <string.h> 
#include <ctype.h> 

int main(void){ 
    printf("Enter your name: "); 
    //User input for string 
    string s = get_string(); 
    int i = 0; 
    //Determine whether the first chars are space - if not print char 
    if(!isspace(s[0])){ 
      printf("%c",s[0]); 
     } 
    i++; 
    //loop through each Char - determine char is not space 
    while(s[i] != '\0'){ 
     if(s[i-1]==' ' && s[i] != ' '){ 
      //if i'th char is space - add one to it thus printing char that comes after space 
      printf("%c", toupper(s[i])); 
     } 
     //advance i'th char count 
     i++; 
    } 
    printf("\n"); 
} 

首先它檢查的天氣前一個字符是空間或沒有,如果是空間則檢查當前字符是否是空間或者沒有,如果它不是空間打印當前字符,否則不行。

希望這會有所幫助。

1

我會以不同的方式處理原始文件和@yajiv的回答,避免字符串中第一個字符出現「特殊情況代碼」。

我想通過列表中的一個運行,並使用一些「狀態」來知道何時輸出一個字符。

  • 當我們看到我們知道,我們要輸出的下一個非空的空間(所以我們設定printNextNonSpace

  • 當我們看到一個非空間,我們打印出來,如果printNextNonSpace設置(後我們清除printNextNonSpace以避免打印額外的字符)

  • printNextNonSpace最初設置爲1,因此我們打印字符串中的第一個字符,如果它不是空格。

注意,這將處理任意數量的空格任何地方串"Andrew Bill Charlie" -> "ABC"中," David Edgar Frank " -> "DEF"

[代碼移除OP明智地想提示放在盤子裏沒有回答]

+0

您是否建議我使用for循環遍歷char數組並從for內部調用printNextNonSpace函數? –

+0

不可以。您仍然可以使用while循環,並且不需要額外的功能 - 只需一個標誌,以便知道是否打印當前正在查看的字符。 – John3136

相關問題