【发布时间】: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 << "Your full name is: " << full_name << endl;之前添加full_name[i] = '\0';。
标签: c++