2014-01-29 175 views
0

我试图写一个代码,要求用户输入一个字符串,并采取除字母以外的所有字符。删除一个字符串的字符

现在我自己做了,它似乎不能正常工作。我是新来的字符串,所以我试图理解和掌握字符串。我试图在Mac上使用gdb,但我没有所有的功能来理解这一点。 你能帮忙吗?

什么代码必须做到:(例如)用户输入:h**#el(l)o&^w

和输出hello.

这里是我的代码:

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

int main() 
{ 
    char string[100]; 
    int i; 
    int seen = 0; 

    printf("Enter String: "); 
    scanf("%s", string); 

    for (i=0; string[i]!='\0'; i++) 
    { 
     if (((string[i]<='a' || string[i]>'z')&&(string[i]<='A' || string[i]>'Z')) ||string[i]!='\0') 
     { 
      seen = 1; 
     } 
     else 
      seen = 0; 
    } 
    if (seen==0) 
    { 
     printf("%s", string); 
    } 
} 
+0

你能告诉你得到的是什么样的输出没有预料到......即有什么问题? – zmo

+0

凌晨程序跳过我的声明并关闭。 – user2985083

回答

0

好了,你的代码有一对夫妇的重要问题:

所以基本上,你会希望是用fgets()而不是scanf()

但是,为什么不只是通过字符得到输入字符,并建立一个只有你想要的字符的字符串呢?它更简单和灵活!

基本上是:

#include <ctype.h> 

int main() { 
    char* string[100]; 
    int i=0; 

    printf("Enter your string: "); 

    do { 
     // getting a character 
     char c = getchar(); 
     // if the character is alpha 
     if (isalpha(c) != 0) 
      // we place the character to the current position and then increment the index 
      string[i++] = c; 
     // otherwise if c is a carriage return 
     else if (c == '\r') { 
      c = getchar(); // get rid of \n 
      // we end the string 
      string[i] = '\0' 
     }else if (c == '\n') 
      // we end the string 
      string[i] = '\0'; 
    // while c is not a carriage return or i is not out of boundaries 
    } while (c != '\n' || i < 100); 
    // if we've got to the boundary, replace last character with end of string 
    if (i == 100) 
     string[i] = '\0'; 
    // print out! 
    printf("Here's your stripped string: %s\n", string); 

    return 0; 
} 

我没有在我的电脑上运行它,因为它已经很晚了,所以我在错误的情况下道歉。

附录:

凌晨程序跳过我的发言,并关闭

那是因为你的状态反转,并删除\0条件,因为它总是与scanf()总是发生将\0附加到字符串以结束它。尝试更换seen = 1seen = 0或尝试使用以下条件:

if ((string[i]>='a' && string[i]<='z')||(string[i]>='A' && string[i]<='Z'))) 
     seen = 1; 
    else 
     seen = 0; 

或简单地说,使用​​的isalpha()功能,就像在我们的两个例子!

+0

如果您想读取多个值,'fgets'可能是更好的选择。对于单个字符串,我认为它不会比scanf(“%99s”,string)'提供更好的缓冲区溢出保护。 – simonc

+0

@zmo真的非常感谢你的努力,从我看到的也是一个好主意,但我主要试图理解并试图做复杂的事情 – user2985083

+1

很好理解什么是错的,当它不起作用。但是要记住,你写的代码量越少,代码就越简单,就会有越少的错误......越容易重读代码! – zmo

0

没有部分(删除多余的字符)来更改代码中的字符串。

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

char *filter(char *string, int (*test)(int)) { 
    char *from, *to; 
    for(to = from = string;*from;++from){ 
     if(test(*from)) 
      *to++ = *from; 
    } 
    *to = '\0'; 
    return string; 
} 

int main(){ 
    char string[100]; 
    printf("Enter String: "); 
    scanf("%99s", string); 
    printf("%s\n", filter(string, isalpha)); 

    return 0; 
}