用 C 编写一个程序,从字符串中删除前导空格和尾随空格

Write a program in C that removes leading and trailing spaces from a string

这是 Thareja 的数据结构和算法教科书中的一道题。我正在尝试解决为我的数据结构准备的问题 class。我正在 https://www.onlinegdb.com/online_c_compiler 编译并 运行。我的程序出现了分段错误,它永远不会进入 if 语句(我似乎无法找出原因)。这个问题可能是微不足道的,我忽略了它,但我希望有另一双眼睛来审视它。

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

int main()
{
    char str[100],ans[100];
    int i=0,j=0;
    clrscr();
    printf("\nEnter string: ");
    gets(str);

    while(str[i]!='[=10=]')
    {
        if(str[i]==' ')
        {
            i++;
            continue;
        } 
        ans[j]=str[i];
        j++;
    }
    ans[j]='[=10=]';
    printf("\nThe string is: ");
    puts(ans);
    getch();
    return 0;
}

感谢您的帮助。

对我来说,问题似乎出在变量 i 上的递增运算符上。 假设用户输入的字符串不为空,并且没有前导 space(s)。 在这种情况下,您的代码成功进入 while 循环(因为它找不到空字符),接下来它检查是否是空白 space (str[i]==' ') ,根据假设不是这样它移动on 将字符存储在 ans[j] 中。 在这一点上一切看起来都很好,但是程序移动到下一行你的代码递增 j 但是 i 呢?通过不递增 i ,您正在使 while 循环进入无限循环。 希望这有帮助。