ReganYue 2020-06-11 11:45 采纳率: 0%
浏览 253

求大佬解答,为什么这段代码用devC++运行正常,但是放PTA会出现段错误。

本题目要求读入一行字符串,去掉首,尾的多余空格后输出。

输入格式:
一个字符串,长度不限,以换行表示结束,但程序要求读取个数不超过30个。

输出格式:
在一对[]中先输出读入的字符串,再在下一行的一对[]中输出去掉首尾空格后的字符串。

输入样例:
湖北 襄阳

输出样例:
[ 湖北 襄阳 ]
[湖北 襄阳]

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str_1[1000]= {0},str_2[1000]= {0},str_3[1000]= {0};
void trim(char * str) {
    int index, i;

    /*
     * Trim leading white spaces
     */
    index = 0;
    while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n') {
        index++;
    }

    /* Shift all trailing characters to its left */
    i = 0;
    while(str[i + index] != '\0') {
        str[i] = str[i + index];
        i++;
    }
    str[i] = '\0'; // Terminate string with NULL


    /*
     * Trim trailing white spaces
     */
    i = 0;
    index = -1;
    while(str[i] != '\0') {
        if(str[i] != ' ' && str[i] != '\t' && str[i] != '\n') {
            index = i;
        }

        i++;
    }

    /* Mark the next character to last non white space character as NULL */
    str[index + 1] = '\0';
}
int main() {

    scanf("%c",&str_1[0]);
    int p=0;
    while(str_1[p]!='\n') {
        p++;
        scanf("%c",&str_1[p]);
    }
    str_2[0]='[';
    for(int i=1; i<p; i++) {
        str_2[i]=str_1[i-1];
    }
    str_2[p+1]=']';

    for(int j=0; j<=p+1; j++) {
        printf("%c",str_2[j]);
    }
    printf("\n");

    trim(str_1);

    printf("[");
    printf("%s",str_1);
    printf("]");
    return 0;
}
  • 写回答

1条回答 默认 最新

  • 关注
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题