【问题标题】:Vector char strange chars矢量 char 奇怪的字符
【发布时间】:2017-05-23 14:01:30
【问题描述】:

有人知道如何复制到字符串吗?因为我使用了函数 strcpy 但是当我打印结果时它显示奇怪的字符。我想连接“姓名”+“@”+“电子邮件”。使用 scanf 我必须将字符 null '\0'?

#include <stdio.h>
#include <string.h>
int main (){

    char message[150];
    char name[150];
    char mail[150];
    char result[150];
    printf("Introduce name: \n");
    scanf("%s",message);
    printf("Introduce email \n");
    scanf("%s",server);
    strcpy(result,message);
    result[strlen(result)]='@'; 
    strcpy(&result[strlen(result)],server);
    printf("RESULT: %s\n",result);
    return 0;
 }

【问题讨论】:

  • result[strlen(result)]='@'; 将删除字符串的 0 终止符。你试过strcat吗?
  • 这也取决于server是什么以及是否溢出缓冲区result
  • snprintf(result, sizeof result, "%s@%s", message, server);,还有char mail[150]; --> char server[150];

标签: c char printf strcpy


【解决方案1】:

result[strlen(result)]='@'; 覆盖由strcpy(result,message); 引入result 的NUL 终止符。所以后续strlen 的结果是未定义的。

更好的解决方案是使用strncat,或者你可以不用写了

char result[150] = {'\0'};

这将初始化整个数组。

但是您仍然冒着溢出result 数组的风险。您可以使用更安全的strncpy 来避免这种情况。更好的是,使用 snprintf 并让 C 标准库为您执行连接。

【讨论】:

  • 是的,一定要使用snprintf(result, sizeof result, "%s@%s", message, server);。还要考虑更好的变量名称,它们与提示不太匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2011-03-09
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多