2016-11-28 43 views
1

我最近开始学习C,并且偶然发现了这个练习。我试图找到所有以同一封信开头和结尾的单词。听起来很容易,但我不知道如何让我的程序重复数组中的每个单词的操作。C - 以相同字母开头和结尾的单词

浏览网页后,我决定使用strtok,将数组分成单词,然后检查每个单词是否以相同的字母开头和结尾。我结束了这段代码,但它不工作,但编译器也没有显示任何问题。

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 

main(){ 
    int i; 
    int found = 0; 
    char arr[1000]; 
    char *token; 
    const char s[2] = " "; 

    printf("Write your line:\n"); 
    scanf("%s", arr); 
    token = strtok(arr, s); 

    while(token!=NULL){ 
     if(token[0] == (strlen(token)-1)){ 
      found++; 
     } 

     token = strtok(NULL, s); 
    } 

    if(found > 0){ 
     printf("Found %d words that start and end with the same letter.\n", found); 
    } 

    return 0; 
} 

任何人都可以向我解释我做错了什么?我一直在看它几个小时,我不知道有什么问题。

+2

'''if(token [0] == token [strlen(token)-1])''' – Ronald

+1

另外'scanf(“%s”,arr);'总是只接受一个单词。 – BLUEPIXY

+0

@Ronald我试过了,但它只适用于第一个单词,忽略了其余 – Swaglina

回答

0

更改的scanf到获取和

f(token[0] == token[strlen(token)-1] 

的scanf认为空格作为输入provided.You也可以使用符%[^ \ n]的下scanf的,这主要是告诉scanf的到的端部扫描输入直到出现“\ n”。
%[^ \ n]的缺点是,如果您试图多次运行该程序,它将不起作用,因为scanf从stdin获取它的输入。由于stdin中的最后一个字符将是最后一个“\” n“或输入你提供的,它基本上会继续跳过,下一个输入,使得gets()成为更好的选择。

相关问题