【问题标题】:Program Crashed (String Manipulation) [closed]程序崩溃(字符串操作)[关闭]
【发布时间】:2016-03-21 15:42:19
【问题描述】:

Python vs C

程序输出会是这样的:

string1 : stack
string2 : overflow
changed string is : sotvaecrkf

*string1 的第 N 个字符由 string2 的第 N 个字符连接

但是每次我运行并向 string1 和 string2 提供输入时,我的 DevC++ 都会崩溃

C 代码:

#include<stdio.h>
#include<string.h>
void zips();


void main(){
zips();
}


void zips(){

printf("enter string1:");
char s1[120],s2[120],s[120],y,z;
scanf("\n%s",s1);
printf("\nenter string2:");
scanf("\n%s",s2);
int leng,increasedlength,i;
int leng1=strlen(s1),leng2=strlen(s2);
if(leng1==leng2){
    leng=leng1;
}
else if(leng1<leng2){
    increasedlength=leng2-leng1;
    leng=leng2-increasedlength;
}
else{
    increasedlength=leng1-leng2;
    leng=leng1-increasedlength;
}
for(i=0;i<=leng;i++){
    y=s1[i];
    printf("%s",y);
    z=s2[i];
    printf("%s",z);
    strcat(y,z);
}   
}

【问题讨论】:

  • 问题是……?
  • 很难理解您在这里实际要求的内容。你怎么了?另外,你说的串联是什么意思?听起来您实际上并不想连接您的 string1 和 string2。
  • 变量yz单个字符,而不是字符串,因此您不能将它们打印为字符串或在strcat 等字符串函数中使用它们.编译器应该对你拥有的代码发出警告,如果没有启用更多警告。
  • 编辑让程序应该做什么更加清晰,但这里仍然没有问题。
  • 这个问题今天以不同的形式发布了好几次......

标签: c string


【解决方案1】:

大概是这样的。请注意,不能对简单的char 类型进行字符串连接。

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

int main (void) {
    char s1[] = "stack";                            // skipped the string inputs
    char s2[] = "overflow";
    char str[120];
    size_t i;                                       // var type returned by `strlen`
    size_t index = 0;
    size_t leng1 = strlen(s1);
    size_t leng2 = strlen(s2);
    size_t leng = leng1 <= leng2 ? leng1 : leng2;   // ternary operation to get min length
    if(leng == 0 || leng * 3 > sizeof str)
        return 1;                                   // will not fit output string
    for(i = 0; i < leng; i++) {                     // note `<=` changed to `<`
        str[index++] = s1[i];                       // buiuld the output string
        str[index++] = s2[i];
        str[index++] = ' ';                         // pad string
    }
    str[index - 1] = '\0';                          // terminate string
    printf("%s\n", str);
    return 0;
}

程序输出:

so tv ae cr kf

【讨论】:

  • 你需要 if(leng * 3 &gt;= sizeof str) 来解释 nul 字符。
  • @FredK 不,我重写了最后不必要的空间。
  • @FredK... 虽然你已经引起我对长度为 0 的情况的注意,并且我已经对其进行了编辑以捕获它,因为将最终的 nul 写入 str[-1] 将是 未定义的行为
  • @EliasVanOotegem 随时使用strncat 发布答案。
  • @WeatherVane 没有正确阅读问题,认为 OP 只是试图连接 2 个字符串,而不是做这个一个一个的洗牌业务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多