注册 登录
编程论坛 新人交流区

[求助]关于动态内存+cin.get的问题

volvox 发布于 2007-11-18 13:29, 689 次点击

本人是个C++新手,在国外打工,被可恶的BOSS赶鸭子上架编了一个小程序,可是好象运行不正常,请高手帮忙指点一下.

程序要求:
Ask the user how long their name is (问用户的名字是几个字母)
Create an array of chars in dynamic memory large enough to store the name
Ask the user to enter their name
Read the name into the array (assume it may include spaces)
Output the name
Delete the array from dynamic memory

程序如下:

#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
int n;
char *a;
cout<<"How many character of your name ";
cin>>n;

int m=n+5;
a=new char[m];

cout<<"Pleas enter your name: ";
cin.get(a,m);//此处能编译但无法运行,程序运行到此便结束
cout << a;

delete[] a;
system("PAUSE");
return 0;
}



故障

见倒数第七行中的"//此处能编译但无法运行,程序运行到此便结束,有个朋友说是内存问题,但不知如何解决."

请高手帮忙看看是什么问题!!!不胜感激.

3 回复
#2
光的赞歌2007-11-18 13:41
我没学好,不太懂,呵呵………………………………………………6
#3
xiaot17292007-11-18 13:58
回复:(volvox)[求助]关于动态内存+cin.get的问题

你在 cin.get(a,m);//此处能编译但无法运行,程序运行到此便结束
之前加一句cin.getline(a,2);就可以了。要不程序会把"回车键"赋给a。
#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
int n;
char *a;
cout<<"How many character of your name ";
cin>>n;

int m=n+5;
a=new char[m];

cout<<"Pleas enter your name: ";
cin.getline(a,2);
cin.get(a,m);//此处能编译但无法运行,程序运行到此便结束

cout << a;

delete[] a;
system("PAUSE");
return 0;
}

#4
volvox2007-11-18 14:18
谢谢楼上的热心朋友,不过,我按以上所说试了一下,好象还是不行啊.直接就退出了.

:-(
1