【发布时间】:2012-05-07 10:14:27
【问题描述】:
谁能告诉我为什么下面给出的代码会出现意外的运行时错误。它适用于两次迭代,但不止于此。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void print(string hmm)
{
ofstream ko(hmm.c_str(),ios::trunc);
ko<<"chacho";
ko.close();
}
int main(){
for(int i=0;i<5;i++)
{
char *chat=new char;
sprintf(chat,"%d%s",i,"_num.txt");
string rat=chat;
print(rat);
}
system("pause");
return 0;
}
【问题讨论】:
-
#define BUF_LEN (256) ...... char *chat=new char[BUF_LEN]; ...... dlete[] 聊天;
-
@neohope,定义根本不适合这个目的。在 C++ 中有许多更好的方法可以做到这一点。此外,分配带有新需求方括号的数组。
-
@neohope,
const在您需要的函数中会更可取,但您可以在类中使用静态 const 或在命名空间中使用 const。即使是全局命名空间中的 const 也比定义好得多,因为定义在编译器启动之前进行并忽略范围。如果有任何形式的冲突,您将浪费一些时间试图弄清楚您遇到的奇怪错误是什么。这是之前回答的问题的链接:stackoverflow.com/questions/4715831/… -
谢谢你,克里斯 :),你是对的。我在 c++ 中没有大量使用命名空间,你的方式更好。
标签: c++