注册 登录
编程论坛 C++教室

初学者关于编程习题求赐教。

一心一意 发布于 2012-07-30 17:59, 873 次点击
#include<iostream>
#include<cstring>
int main()
{
    using namespace std;
    const int size=20;
    char firstname[size];
    char lastname[size];
    char fullname[2*size+1];
    cout<<"enter your fist name:";
    cin>>firstname;
    cout<<"enter your last name:";
    cin>>lastname;
    strncpy(fullname,lastname,size);
    strcat(fullname,",");
    strncat(fullname,firstname, size);
    fullname[size-1];
    cout<<"here's the information in a single string:"<<fullname<<endl;
    return 0;
}
上面红色字的地方不太明白,就是[2*size+1]和[size-1]是什么意思或者起了什么作用?本人愚笨自学看书没看懂,希望好心人能帮帮我,最好能解释的直白一点,哈。
   
   

   
13 回复
#2
zklhp2012-07-30 18:55
不知道你看的什么书 感觉这样实现不大好啊 当然 其实我不会C++
#3
zklhp2012-07-30 18:58
但这个其实和C++没特别大的关系

  char fullname[2*size+1];

就是定义了一个数组 仅此而已

fullname[size-1];

这有啥深刻含义呢 我也不知道了
#4
pangding2012-07-30 21:59
后面那句没什么意义吧。
#5
zklhp2012-07-30 22:04
大牛都说没意义了

不知道楼主看的什么书 呵呵
#6
遗失的部落2012-07-31 01:30
  表示不理解
#7
peach54602012-07-31 08:26
唉,定义了size是20

然后first name20
lastname20
fullname可不就是2*size吗?
#8
gaigai1232012-07-31 09:25
唉,定义了size是20
 
然后first name20
 lastname20
 fullname可不就是2*size吗?
不是20.还有一个逗号啊,哈哈哈,不过最后突然冒出了fullname[size-1];不知道何意
#9
一心一意2012-07-31 11:14
谢谢楼上各位好心人,我看的是c++ primer第5版,这是上面的习题,网上找了所谓的标准答案就是那样写的。看了大家的见解应该是理解了[2*size+1]的意思,另一个还是没有理解过来,因为即使去掉了[size-1]程序也能照常运行,没有提出警告。
#10
qq3785081452012-07-31 13:51
此书坑人甚深,可扔之另寻也
#11
bei0405492012-08-02 00:34
就是定义了两个数组嘛!
#12
hehe738519122012-08-03 17:02
const int size=20;定义了 size = 20
char fullname[2*size+1];   这个意思是 定义了  一个 字符数组  数组名是    fullname   数组的元素是41个   直白点就是   char fullname[41]; 就这么简单  
仅仅 是个人看法  不对的话 楼主无怪  并且告我一下  谢谢
#13
lsnaimei2012-08-03 22:27
个人觉得这本书不适合像你这样的初学者
#14
粉红木耳2012-08-05 10:53
字符数组 +  "\0" 结束字符
所以 size +1;
strncat(fullname,firstname, size); 连接后要 - “\0”固然有以下代码
fullname[size-1];
1