当sprintf遇到string

       一直都知道sprintf使用string参数时一定要用.c_str()转换为char*之后才行,否则就会出现“(NULL)”。一次疏忽,在sprintf中发现“(NULL)”,但是此参数是一个char*,无论如何找不到char*成为“(NULL)”的原因。后对sprintf的每次参数详细检查时才发现这个char*前一个参数是string,忘了转成char*,它自己没有变成“(NULL)”,而导致后面的参数成了“(NULL)”。

     其次也发现定义char[]全局变量时,一定得初始化,否则在使用时会造成千奇百怪的问题。

     某次定义了全局变量int  gPCID;char gKey[32];

     读取文本配置文件时,逐行读取并分配给gPCID、gKey。gPCID读取时正常,一旦gKey读取后,gPCID就改变了数值。查找了很久才发现原因。

     留下测试证据:

#include 
#pragma hdrstop

#include "Unit1.h"

#include 
#include 
#include 
using namespace std;
int  gPCID;
char gKey[32];//一定要初始化 ={0}
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
#define DIR "D:\\Program Files\\NoDel.dat"
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    try
    {
        char line[64] = {0};     //读取授权码
        std::ifstream openfile(DIR, std::ios::in);
        openfile.getline(line, sizeof(line));
        gPCID = atoi(line);

        openfile.getline(line, sizeof(line));
        //string s= line;//此行读取后不会改变gPCID值,若替换成下行则会
        strcpy(gKey, line);
        openfile.close();
    }
    catch(...)
    {

    }

}

 

你可能感兴趣的:(bcb,C++)