C++程序编译后运行输出异常但Visual Studio调试正常的问题求助
C++程序编译后运行输出异常但Visual Studio调试正常的问题求助
各位大佬好,我最近写了个C++小工具,功能是接收用户输入的字符串,然后通过三个函数分别添加两个随机单词、三个随机数字和三个随机符号来生成更安全的新密码。但遇到了一个特别奇怪的问题:
在Visual Studio的本地调试器里运行时,一切都正常——比如我输入test,调用添加两个单词的函数后,能得到test-Acrydium-Birkenhead这样符合预期的结果;但如果直接编译生成可执行文件后运行,输出就完全不对了,同样输入test,结果变成了test--,根本没把随机单词加进去。
先给大家贴一下我的代码:
添加两个随机单词的函数
这个函数会从word.txt文件里随机选两个单词,用连字符拼接到原密码后面:
string addWords(string oldPassword) { ifstream file("word.txt"); int times = 0; while (times < 2) { int number = rand() % 1000; // 随机取0-999的数字,对应word.txt里的1000行单词 string word = ""; // 重置文件指针到文件开头 file.clear(); file.seekg(0, ios::beg); // 逐行读取直到到达随机指定的行 for (int i = 0; i < number; ++i) { getline(file, word); } // 把选中的单词拼接到原密码后 oldPassword += "-" + word; times += 1; } file.close(); return oldPassword; }
添加三个随机数字的函数
这个函数会在原密码的随机位置插入三个0-9的随机数字:
string addDigits(string oldPassword) { for (int i = 0; i <= 2; i++) { int randomINT = rand() % 10; int randomPOS = rand() % oldPassword.length(); char c = '0' + randomINT; oldPassword.insert(randomPOS, 1, c); } return oldPassword; }
添加三个随机符号的函数
这个函数会在原密码的随机位置插入三个从符号池里选的随机符号:
string addSymbols(string oldPassword) { string randomSymbols = "!$%^&*()[{]}#~@;:/?.>,<|"; for (int i = 0; i <= 2; i++) { int randomINT = rand() % randomSymbols.length(); char randomChar = randomSymbols[randomINT]; int randomPOS = rand() % oldPassword.length(); oldPassword.insert(randomPOS, 1, randomChar); } return oldPassword; }
输出新密码的函数
最后用这个函数输出生成好的新密码:
void displaynewPassword(string newPassword) { cout << ("Your new password is: " + newPassword); cout.flush(); system("pause"); }
补充一下:我把word.txt文件放在了Visual Studio的“源文件”目录下,调试的时候程序能正常读取到这个文件里的单词,但直接编译运行可执行文件时,好像就找不到这个文件了?
有没有大佬能帮我分析下这是哪里出了问题?为什么调试和直接运行的结果会不一样?
内容来源于stack exchange
相关产品推荐
相关产品推荐

