2015-10-14 184 views
-7

我是C编程的新手,我知道有关于如何将字符串拆分为单词的其他解释,但没有一个与我的程序类似。我很难找到我的程序中的错误:Tokenise在C编程中的字符串

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

int tokenise(char str[], int start, char result[]) { 
    if (str[start] == "/o") { 
     return -1; 
    } else { 
     result = str[start]; 
    } 
} 


int main() {  
    const int MAX_STRING = 256; 
    char buffer[MAX_STRING]; 
    fgets(buffer, MAX_STRING, stdin); 
    char result[256]; 
    int start; 
    start = tokenise(buffer, 0, result); 

    while (start != -1) { 
     printf("%s\n", result); 
     start = tokenise(buffer, start, result); 
    } 
} 
+5

您是否有真正的问题? –

+1

请在将来使用正确的缩进;它会让你的生活变得更加轻松,人们更有可能回答你的问题。这次我已经为你修好了。此外,此代码不能编译。 – szczurcio

+0

是的,我的程序不会工作,我不知道为什么 – bike3

回答

4

在你的函数tokenise -

if(str[start] == "/o"){ 

什么"/o"你比?它应该是'\0'

if(str[start] == '\0'){ 

而且在else你的功能不return什么,因此,在这种情况下UB。

您的函数没有任何循环或使用递归遍历数组,因此,您的逻辑似乎没有实现任何接近。

+0

这不是这个代码中最大的问题,不能用'=='比较'char'和'const char *',或者用'='赋值。 – szczurcio

+0

@szczurcio这就是它的要点。他应该与空字符比较。由于OP的逻辑被破坏,它没有任何意义。 – ameyCU

+0

啊是的,没有注意到单引号,你是对的。 – szczurcio

3

你有很多问题,你的代码:

else { 
    result = str[start]; 
} 

无返回值。这是未定义的行为。

str[start] == '\o' 

那是不正确的,你要比较的EOS空终止字符 而是执行此操作:

str[start] == '\0' 

最后,如果你希望你的tokenise函数写成result,你需要通过一个指向result的指针,而不是result的值。

ps:除了语义错误之外,你的函数并没有类似你想要的东西。研究循环及其实现。

+0

'\ 0'不是EOF,而是EOS。 – sbi