c++中的(cin>>)怎么用 (我是新手请说 林宥嘉的普及点)

一开始搞来搞去发现总是没办法显示最后一个数的time,然后现在的代码是输入数字回车,显示除了最后一个其余数字的出现次数,之后按Ctrl+Z,再按回车(跳出while循环),就会显示按任意键继续,就可以执行下面的代码了。#include&iostream&int main(){ int currVal = 0, val = 0; int cnt = 0; if (cin && currVal){
cout && &开始& &&
while (cin && val){
if (val == currVal)
cout && &计数& &&
cout && currVal && & occurs & && cnt && & times & &&
cout && &换数&&&
cout && currVal && & occurs & && cnt && & times & && } system(&PAUSE&); cout && &end& && system(&PAUSE&);return 0;}
最新教程周点击榜
微信扫一扫啰啰嗦嗦学习VC++_&&第二课:掌握C++&& - liqiangzk982的博客 - 编程中国
啰啰嗦嗦学习VC++_&&第二课:掌握C++&&
第二课:掌握C++
增加了软件的可扩充性和代码的重用性。多态性使程序设计人员在设计程序时可以对问题更好的抽象,有利于代码的维护和可重用。
File -& New -& Project() -& Win32 Console Application() -&
File -& New -& Files -& C++ Source File -& File: Point
#include &iostream.h&
struct Point
}; &&&&&&&//
void main()
&&&&&& pt.x=5;
&&&&&& pt.y=5;
&&&&&& cout&&pt.x&&endl&&pt.y&& //coutprintf
#include &iostream.h&
struct Point
};&&&&&&& //
void main()
&&&&&& pt.x=5;
&&&&&& pt.y=5;
&&&&&& cout&&pt.x&&endl&&pt.y&& //coutprintf
&&&&&& cout&&"please input : pt.x = "&&
&&&&&& cin&&pt.x;
&&&&&& cout&&"please input : pt.y = "&&
&&& cin&&pt.y;
&&&&&& cout&&pt.x&&endl&&pt.y&& //coutprintf
C++cincoutcerrcstdinstdoutstderr()
cin&&coutcerr&&
cincoutCscanfprintfcincoutscanfprintf
endl(end of line),endlc’\n’
#include &iostream.h&
#include &iostream.h&
struct Point&&&&& &//
&&&&&& void output()&&& //cc++
&&&&&&&&&&&&& cout&&x&&endl&&y&&
void main()
&&&&&& pt.x=5;
&&&&&& pt.y=5;
&&&&&& pt.output();&&&& //
//&&&& cout&&pt.x&&endl&&pt.y&&
’struct Point’’class Point’’public:’
#include &iostream.h&
//struct Point&& //
class Point&&& // struct Pointclass Point
public:&&&&&& //class Point
&&&&&& void output()
&&&&&&&&&&&&& cout&&x&&endl&&y&&
&void main()
&&&&&& pt.x=5;
&&&&&& pt.y=5;
&&&&&& pt.output();
//&&&& cout&&pt.x&&endl&&pt.y&&
c++structStructclass
classpublic cannot access private member declared in class 'Point'
’public’;’private’,c++
public,private,protected
#include &iostream.h&
struct Point
//class Point
&&&&&& void output()
&&&&&&&&&&&&& cout&&x&&endl&&y&&
void main()
&&&&&& pt.x=5;
&&&&&& pt.y=5;
&&&&&& pt.output();
//&&&& cout&&pt.x&&endl&&pt.y&&
classpublic
structclassstructpublicclassprivateC++
P PointptPoint””
具有具体属性值。
#include &iostream.h&
class Point
&&&&&& void output()
&&&&&&&&&&&&& cout&&x&&endl&&y&&
void main()
//&&&& pt.x=5;
//&&&& pt.y=5;
&&&&&& pt.output();
//&&&& cout&&pt.x&&endl&&pt.y&&
Press any key to continue
void init()
*void init()
#include &iostream.h&
class Point&&&&&&&&&&&&& &//
&&&&&& void init()&&&&&&&&& // void init()
&&&&&& {&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& {
浏览12140次
(2758)(1753)(1045)(1029)(927)(815)(761)(758)(595)(560)It's me again probably asking noob C++ questions
I had MAJOR headaches making the darn (sorry for the language) MySQL C++ connector work. I don't know if it is poorly written or something, but for my experience yet I've never had so much trouble making something to work.
Anyhow I got it to connect and throw exceptions on failed connect/query which for me is quite big thing :U :P . The actual problem comes out of me obtaining the result of the query. Regardless of what I do my application always crashes :S
I used the 32-bit installer and the libmysql.dll/lib from the 32-bit MySQL server (since i'm compiling a 32-bit application i figured this is the right thing to do)
Here's some code so you could imagine what I'm talking about
DBManager.h
#ifndef DBMANAGER_H
#define DBMANAGER_H
#define CPPCONN_PUBLIC_FUNC
#define CPPCONN_LIB_BUILD True
#include &string&
#include "mysql_connection.h"
#include "mysql_driver.h"
#include &cppconn/driver.h&
#include &cppconn/exception.h&
#include &cppconn/resultset.h&
#include &cppconn/statement.h&
#include &cppconn/prepared_statement.h&
class DBManager
static DBManager* Instance();
bool Query(const char* Query);
void Connect(const char* DbHost, unsigned short DbPort, const char* DbUser, const char* DbPass, const char* DbName);
bool ValidCredentials(const char* Username, const char* Password);
void ManageException(sql::SQLException &e);
~DBManager();
protected:
static DBManager* pI
DBManager() {};
DBManager(DBManager const&){};
DBManager& operator=(DBManager const&){};
sql::mysql::MySQL_Driver*
sql::Connection *C
sql::PreparedStatement *
sql::ResultSet *
sql::Statement *
And now the cpp file DBManager.cpp
#include "DBManager.h"
DBManager* DBManager::pInstance = NULL;
DBManager* DBManager::Instance()
if (!pInstance)
pInstance = new DBManager();
bool DBManager::Query(const char* Query)
DBManager::~DBManager()
void DBManager::ManageException(sql::SQLException& e)
if (e.getErrorCode() != 0) {
std::cout && "# ERR: SQLException in " && __FILE__;
std::cout && "(" && __FUNCTION__ && ") on line " && __LINE__ && std::
std::cout && "# ERR: " && e.what();
std::cout && " (MySQL error code: " && e.getErrorCode();
std::cout && ", SQLState: " && e.getSQLState() && " )" && std::
void DBManager::Connect(const char* DbHost, unsigned short DbPort, const char* DbUser, const char* DbPass, const char* DbName)
driver = sql::mysql::get_mysql_driver_instance();
std::string connDSN = "tcp://" + std::string(DbHost) + ":3306";
Con = driver-&connect(connDSN, sql::SQLString(DbUser), sql::SQLString(DbPass));
Con-&setSchema(sql::SQLString(DbName));
isConnected =
std::cout&&"Database connection successul."&&std::
} catch(sql::SQLException &e) {
ManageException(e);
isConnected =
bool DBManager::ValidCredentials(const char* Username, const char* Password)
bool cred =
pstmt = Con-&prepareStatement("SELECT * FROM account WHERE account_name=? LIMIT 1"); // Smart use of indexing
pstmt-&setString(1, Username);
res = pstmt-&executeQuery();
while(res-&next())
if (res-&getString("password") == Password)
catch(sql::SQLException &e) {
ManageException(e);
Basically, It compiles without a problem, Connects without a problem, Executes queries without a problem, but the second I try to retrieve data some breakpoint exception is thrown in a file "xutils.cpp". I really have no idea what I'm doing wrong. I'm using the DEBUG libraries while compiling for debug. Hmm libmysql.dll should be release since I extracted it from the server bundle, but I don't seem to find it as a source to compile my own.
I really have no idea why it crashes and burn like that :/
PS: Don't mind the no hashing of the password, it really is just a proof of concept to me in the way of ... getting it to work first, then securing it :U
PS: I also have Boost libraries compiled and ready in the project, if that would help :U
EDIT: Main function
bool ServerRunning =
int main(int argc, char** argv)
#ifdef _WIN32
std::string title = TEXT("Window Title Change");
SetConsoleTitle(title.c_str());
std::cout&&"Loading Configuration File..."&&std::endl&&std::
std::string path = boost::filesystem::path(boost::filesystem::current_path()).string();
path += "\\Config.ini";
INIParser* Config = new INIParser(path.c_str()); //MinINI
// Sockets data
std::string listenIP = Config-&GetString("Network", "ListenIP", "127.0.0.1");
unsigned short listenPort = Config-&GetInt("Network", "ListenPort", 5000);
// Database data
std::string dbHost = Config-&GetString("Database", "Host", "localhost");
std::string dbUser = Config-&GetString("Database", "User", "root");
std::string dbPass = Config-&GetString("Database", "Password", "");
std::string dbName = Config-&GetString("Database", "Database", "authserv");
unsigned short dbPort = Config-&GetInt("Database", "Post", 1000);
// General settings
int sessionTimeout = Config-&GetInt("Settings", "SessionTimeout", 10);
int maxClients = Config-&GetInt("Settings", "MaxClients", 10);
int serverTimeout = Config-&GetInt("Settings", "GameserverTimeout", 1);
// Begin Initialization
DBManager::Instance()-&Connect(dbHost.c_str(), dbPort, dbUser.c_str(), dbPass.c_str(), dbName.c_str());
bool loginSuccess = DBManager::Instance()-&ValidCredentials("Username", "Password");
while (ServerRunning)
std::cin&&c;
if (c == 'q')
ServerRunning =
解决方案 Assuming the password field is defined as varchar in the database, you cannot use getString() to retrieve it.
You must instead use the blob function, getBlob().
This is how the while loop would look:
while(res-&next())
std::istream * retrievedPassword_stream = res-&getBlob("password");
if (retrievedPassword_stream)
char pws[PASSWORD_LENGTH+1]; // PASSWORD_LENGTH or use other functions to retrieve it
retrievedPassword_stream-&getline(pws, PASSWORD_LENGTH);
std::string retrievedPassword(pws); // also, should handle case where Password length & PASSWORD_LENGTH
if (retrievedPassword == std::string(Password))
Side comments: Note that there are some other issues with the code.
The statement handle must be deleted, so you shou at the appropriate place in the ValidCredentials() function (rather than in the destructor).
(But, why use a prepared statement in that case anyways?
Better to initialize the prepared statement in the constructor (or somewhere else outside the function the query is called), as well as delete in the destructor or elsewhere, if you do use a prepared statement.
Instead of a prepared statement, though, note that prepared statements are most useful for very high-use and high-CPU intensive queries, so using it for password validation might not be important here (you could just execute a regular query, instead of a prepared statement).)
Likewise, the ResultSet needs to be deleted (delete res) at the end of the try block, rather than in the destructor.
Be sure to check for NULL before using pstmt, res, or Con.
stmt appears to be unused and should not be deleted.
本文地址: &
我有MAJOR的头痛使MySQL的C ++连接器工作的darn(对不起的语言)。我不知道它是写得不好还是什么,但对我的经验,但我从来没有这么多麻烦使工作。
无论如何我得到它连接和抛出异常连接/查询失败,对我来说是相当大的事:U:P。实际的问题是从我获得查询的结果。无论我做什么我的应用程序总是崩溃:S
我使用32位安装程序和libmysql.dll / lib从32位MySQL服务器编译一个32位应用程序,我想这是正确的事情)
这里有一些代码,所以你可以想象我在说什么
DBManager.h
#ifndef DBMANAGER_H
#define DBMANAGER_H
#define CPPCONN_PUBLIC_FUNC
#define CPPCONN_LIB_BUILD True
#include& string&
#include“mysql_connection.h” #include“mysql_driver.h” #include& cppconn / driver.h&
#include& cppconn / exception.h&
#include& cppconn / resultset.h&
#include& cppconn / statement.h&
#include& cppconn / prepared_statement.h&
class DBManager
{ public: static DBManager * Instance();
bool Query(const char * Query);
void Connect(const char * DbHost,unsigned short DbPort,const char * DbUser,const char * DbPass,const char * DbName);
bool ValidCredentials(const char * Username,const char * Password);
void ManageException(sql :: SQLException& e);
?DBManager();
protected: static DBManager * pI
private: DBManager(){};
DBManager(DBManager const&){};
DBManager& operator =(DBManager const&){};
sql :: mysql :: MySQL_Driver *
sql :: Connection * C
sql :: PreparedStatement *
sql :: ResultSet *
sql :: Statement *
bool isC };
现在cpp文件 DBManager.cpp
#include“DBManager.h”
DBManager * DBManager :: pInstance =空值;
DBManager * DBManager :: Instance() { if(!pInstance) { pInstance = new DBManager }
return pI }
bool DBManager :: Query(const char * Query) { }
DBManager ::?DBManager() { delete C
void DBManager :: ManageException(sql :: SQLException& e) { if(e.getErrorCode()!= 0){ std :: cout&& “#ERR:SQLException in”& __文件__;
std :: cout&& “”(“&& __FUNCTION__&& __LINE__&& std ::
std :: cout&& “#ERR:”&& e.what();
std :: cout&& “(MySQL错误代码:”<e.getErrorCode();
std :: cout <“,SQLState:”&& e.getSQLState()& && std :: } }
void DBManager :: Connect(const char * DbHost,unsigned short DbPort,const char * DbUser,const char * DbPass,const char * DbName) { try { driver = sql :: mysql :: get_mysql_driver_instance();
std :: string connDSN =“tcp://”+ std :: string(DbHost)+“:3306”;
Con = driver-& connect(connDSN,sql :: SQLString(DbUser),sql :: SQLString(DbPass));
Con-& setSchema(sql :: SQLString(DbName));
isConnected =
std :: cout&&“Database connection successul。”&& std ::
} catch(sql :: SQLException& e){ ManageException(e);
isConnected =
bool DBManager :: ValidCredentials(const char * Username,const char * Password) { bool cred =
try { pstmt = Con-& prepareStatement(“SELECT * FROM account WHERE account_name =?LIMIT 1”); //智能使用索引 pstmt-& setString(1,Username);
res = pstmt-& executeQuery();
while(res-& next()) { if(res-& getString(“password”)== Password) { cred = } } }
catch(sql :: SQLException& e){ ManageException(e);
基本上,它编译没有问题,连接没有问题,一个问题,但第二我尝试检索数据一些断点异常抛出在文件“xutils.cpp”。我真的不知道我做错了什么。我在编译调试时使用DEBUG库。 libmysql.dll应该是发布的,因为我从服务器包中提取它,但我似乎没有找到它作为源编译我自己。
我真的不知道为什么会崩溃和烧伤:/
没有哈希的密码,它真的只是一个概念的证明在我的方式...让它工作第一,然后保护它:U
PS:我也有Boost库编译并准备在项目中,如果这将有助于:U
编辑:主函数
bool ServerRunning =
int main(int argc,char ** argv) { #ifdef _WIN32
std :: string title = TEXT(“窗口标题更改”);
SetConsoleTitle(title.c_str());
std :: cout&&“加载配置文件...”&& std :: endl&& std ::
std :: string path = boost :: filesystem :: path(boost :: filesystem :: current_path())string();
path + =“\\Config.ini”;
INIParser * Config = new INIParser(path.c_str()); // MinINI
//套接字数据 std :: string listenIP = Config-& GetString(“Network”,“ListenIP”,“127.0.0.1”);
unsigned short listenPort = Config-& GetInt(“Network”,“ListenPort”,5000);
//数据库数据 std :: string dbHost = Config-& GetString(“Database”,“Host”,“localhost”);
std :: string dbUser = Config-& GetString(“Database”,“User”,“root”);
std :: string dbPass = Config-& GetString(“Database”,“Password”,“”);
std :: string dbName = Config-& GetString(“Database”,“Database”,“authserv”);
unsigned short dbPort = Config-& GetInt(“Database”,“Post”,1000);
//一般设置 int sessionTimeout = Config-& GetInt(“Settings”,“SessionTimeout”,10);
int maxClients = Config-& GetInt(“Settings”,“MaxClients”,10);
int serverTimeout = Config-& GetInt(“Settings”,“GameserverTimeout”,1);
//开始初始化 DBManager :: Instance() - > Connect(dbHost.c_str(),dbPort,dbUser.c_str(),dbPass.c_str(),dbName.c_str ());
bool loginSuccess = DBManager :: Instance() - & ValidCredentials(“Username”,“Password”);
while(ServerRunning) { std :: cin&&
if(c =='q') { ServerRunning = } }
return 0; }
解决方案 在数据库中定义 password 字段为 varchar ,不能使用 getString()以检索它。您必须改为使用 blob 函数, getBlob()。
这是 while 循环的外观:
while (res-& next()) { std :: istream * retrievedPassword_stream = res-& getBlob(“password”);
if(retrievedPassword_stream) { char pws [PASSWORD_LENGTH + 1]; // PASSWORD_LENGTH或使用其他函数来检索它 retrievedPassword_stream-& getline(pws,PASSWORD_LENGTH);
std :: string获取密码(pws); //也,应该处理密码长度& PASSWORD_LENGTH
if(retrievedPassword == std :: string(Password)) { cred = } } }
请注意,代码还有一些其他问题。
必须删除语句句柄, code> 在 ValidCredentials()函数中的适当位置(而不是析构函数中)。 (但是,为什么在这种情况下使用预准备的语句更好地在构造函数(或调用查询的函数外部的其他地方)中预先准备的语句,以及在析构函数中删除或初始化在其他地方,如果你使用准备语句,而不是准备语句,但是,请注意,准备语句是最有用的非常高使用率和高CPU密集型查询,因此使用它进行密码验证)
同样,ResultSet需要被删除( delete res
请务必在使用 pstmt 之前检查NULL, code>, res 或 Con 。
stmt 似乎未使用,不应删除。
本文地址: &
扫一扫关注官方微信}

我要回帖

更多关于 请说声爱我 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信