【问题标题】:Adding 2 cstring arrays into 1 cstring array将 2 个 cstring 数组添加到 1 个 cstring 数组中
【发布时间】:2020-08-21 09:47:30
【问题描述】:

我最近学习了 cstring 数组,想尝试一个基本的操作,将两个字符串加在一起,在一个普通的字符串中,作为 header 可以添加 string1+string2=string3。但是我尝试为 cstrings 执行此操作,当我遵循这种可能不正确的格式时出现错误。 这是代码,该代码仅用于将我的名字和姓氏打印为字符串中的 1 个名称。

#include<iostream>
#include<cstring>


using namespace std;

 int main() {
 char fname[100], lname[100], full_name[100];
 int i, j;
 i = 0;j = 0; // i is index of fname and j is index for lname
 cout << "Enter your first name: ";
 cin.getline(fname, 100);
 cout << "Enter your last name: ";
 cin.getline(lname, 100);
 for (i;fname[i] != '\0';i++) {
    full_name[i] = fname[i];
  }
  std::string(fname +" "+ lname);
  cout << "i =" << i;
  full_name[i] = ' ';
  i = i + 1;
  for (i, j;lname[j] != '\0';i++, j++) {
    full_name[i] = lname[j];
    }
    cout << "Your full name is: " << full_name << endl;
    system("pause");
    return 0;
}

【问题讨论】:

  • std::string(fname +" "+ lname); -> std::string(fname) +" "+ lname; ?
  • 你忘了空终止full_name
  • strcpy()strcat()(或更安全的 strncpy()strncat())可用于操作 cstrings。
  • 如何对字符串进行空终止?
  • 通过在字符串末尾添加'\0':在这种情况下,在cout &lt;&lt; "Your full name is: " &lt;&lt; full_name &lt;&lt; endl; 之前添加full_name[i] = '\0';

标签: c++


【解决方案1】:

首先从代码中删除这一行

std::string(fname +" "+ lname);

第二次你忘记在结束字符串后添加'\0' 看看这段代码:

int main() {
    char fname[100], lname[100], full_name[100];
    int i, j;
    i = 0; j = 0; // i is index of fname and j is index for lname
    cout << "Enter your first name: ";
    cin.getline(fname, 100);
    cout << "Enter your last name: ";
    cin.getline(lname, 100);
    for (i; fname[i] != '\0'; i++) {
        full_name[i] = fname[i];
    }

    cout << "i =" << i;
    full_name[i] = ' ';
    i = i + 1;
    for (i, j; lname[j] != '\0'; i++, j++) {
        full_name[i] = lname[j];
    }
    full_name[i] = '\0';
    cout << "Your full name is: " << full_name << endl;
    system("pause");
    return 0;
}

【讨论】:

  • 好吧,你的回答修复了代码,谢谢,谢谢@MikeCAT,但你介意解释一下为什么要添加 full_name[i]='\0';有很大的不同吗?字符串中不应该已经声明了 null 吗?
  • 本地char full_name[100];的初始内容是不确定的。它可能为零,但赌它太危险了。另一种方法是通过写入char full_name[100] = ""; 将数组初始化为零
  • @JohnnyJoestar adding full_name[i]='\0' 标记字符串的结尾。详细答案请看这里:stackoverflow.com/questions/40821419/…
  • 谢谢你们的回答,我现在解决了困惑,再次感谢你们。
猜你喜欢
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2021-07-18
  • 2011-04-12
相关资源
最近更新 更多