我的程序有一些问题,我想做的是生成一个 md5
密码,然后将其保存到一个文本文件中,这部分对我不起作用,(“表达式无效空指针”)任何帮助将不胜感激。
C++ Visual Studio 2015
main.cpp
#include <iostream>
#include <istream>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include "s_encrypt.h"
#include "encrypt_copy.h"
using namespace std;
int main(int argc, char *argv[])
{
string password = "";
cout << "Please enter a password to be encrypted\n";
getline(cin, password);
cout << "MD5 Encryption of " << password << " " << "is this" << " " << md5(password);
cout << "Saving MD5 generated password to text file";
std::string p = md5(password);
CopyEncryptedPw(p);
return 0;
}
加密复制.cpp
#include <istream>
#include <iostream>
#include <fstream>
#include <string>
#include "encrypt_copy.h"
using namespace std;
std::string CopyEncryptedPw(std::string pass)
{
fstream outfile;
outfile.open("C:\encrypted_pass.txt", ios::out);
outfile << pass;
return 0;
}
加密复制.h
#pragma once
#ifndef ENCRYPT_H
#define ENCRYPT_H
std::string CopyEncryptedPw(std::string pass);
#endif
最佳答案
您的代码有两个问题:
问题 1:
outfile.open("C:\encrypted_pass.txt", ios::out);
如果我们假设您的操作系统是 Windows,这应该是:
outfile.open("C:\\encrypted_pass.txt", ios::out);
此外,正斜杠可用于标准流函数:
outfile.open("C:/encrypted_pass.txt", ios::out);
问题 2:
你为一个应该返回 std::string
的函数返回了 0。
std::string CopyEncryptedPw(std::string pass)
{
//...
return 0; // <-- This is bad
}
此代码在返回时表现出未定义的行为,因为将发生的是将 0 分配给 std::string
返回值,并将 0 分配给 std::string
是未定义的行为。
返回字符串类型(或可转换为 std::string
的类型),或返回 int
:
int CopyEncryptedPw(std::string pass)
{
fstream outfile;
outfile.open("C:\\encrypted_pass.txt", ios::out);
outfile << pass;
return 0;
}
你也可以有一个不返回任何东西的 void
函数,但你可能想要一个 int
返回值,例如,返回一个错误代码(或 OK指标)。
关于c++ - 表达式无效的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203188/