关于程序运行时字符串的输入

来源:百度知道 编辑:UC知道 时间:2024/06/07 19:37:50
大家好,最近学vc++碰到这个问题,我要输入一串字符串,这个字符串的长度是未知的,比如可能是“loda”,也可能是“vigoss”,怎样写这个程序,而且最后输入的字符串的内容要输出。下面是我写的程序,编译能通过,但是运行时老出现一些问题,请大家帮我改正下。

#include "stdafx.h"
#include "iostream"
using namespace std;

void _tmain(int argc, _TCHAR* argv[])
{
char *file;
file=new char[];
cout<<"please input the files!"<<endl;
scanf("%s", file);
printf("%s", file);
delete []file;
system("pause");
}

运行是会出现这个问题
Windows has triggered a breakpoint in 8_4.exe.

This may be due to a corruption of the heap, and indicates a bug in 8_4.exe or any of the DLLs it has loaded.

The output window may have more diagnostic information

output windows 显示
'8_4.exe': Loaded 'E:\vc_work\8_4\debug\8_4.exe', Symbols loaded.
'8_4.exe': Loaded 'C:\WINDOWS\system32\

用字符数组就可以了,以下代码已经调试通过:
char code[256];
cout<<"please input the files!"<<endl;
cin>>code;
cout<<"Input filename is:"<<code<<endl;

使用 new 从堆上分配内存要指定大小,所以
file=new char[];这句是错的。
读取字符串应该用 gets(char*)。