C++中的字符串溢出?这种无聊的嘟嘟声很奇怪

Cap*_*ing 0 c++ string buffer-overflow

我正在开发一个垃圾文件生成器,但由于某种原因,如果我使用大数字,它将无限地发出哔声,直到文件完成,我认为在ascii表中某处有一个字符,或者它溢出并导致错误蜂鸣声.有人想解释为什么这件事在尖叫我吗?

#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <time.h>
#include <windows.h>
#define print cout<<

using namespace std;

int numberof,i;
char charvalue;
string charlist,filename;

int main()
{
    srand (time(NULL));
    print "What do you want the name of your file to be?(with a .txt extension)\n";
    getline(cin,filename);
    print "\nHow many characters do you want?\n";
    cin>>numberof;

    for(numberof>0;numberof!=0;numberof--)
        {
        i = rand() % 255 + 32;
        charvalue=i;
        charlist=charlist+charvalue;
        print charlist;
        }

    ofstream writefile(filename.c_str());
    writefile<<charlist;
    writefile.close();
    ShellExecute(NULL, "open", filename.c_str(), NULL, NULL, SW_SHOWNORMAL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这一点上似乎字符最终会正常显示,但它只将1/4写入文本文件.谁知道为什么?

Jer*_*fin 7

i = rand()%255 + 32;

您可能希望这类似于:

i = rand()%(255-32)+ 32;

你也真的想摆脱这个:

#define print cout<<
Run Code Online (Sandbox Code Playgroud)

按照目前的情况,当(不是)任何正在评判你的作业的人决定杀了你时,他(她?)几乎肯定会因为它是自卫而被判无罪.

  • @ssen:如果你愿意,可以使用#define,并保证永远不会将代码显示给另一个C++程序员.一些SO用户对此感到困惑.哎呀,我看到并理解了它,然后一分钟后它被它弄糊涂了. (3认同)