我在MFC程序中通过点击按钮打开了一个控制台窗口,执行一些输入输出的功能,图片是运行结束的状态。之后我关闭窗口每次再进的时候都一直是那样,表明每次我点开窗口都无须我自己的输入程序自己就能运行至此,一直想不明白。
void CC350UdpTestDlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
LoadDouble load;
load.length = 0;
char sendBuffer[1000];
memset(&load.container, 0, 100);AllocConsole();
SetConsoleTitle(_T("Input Double Data"));
freopen("CONOUT$", "w", stdout);
freopen("CONIN$", "r", stdin);cout << "Input:" << endl;int i = 0;
while (cin >> load.container[i])
{
    load.length++;
    cout << load.container[i] << " ";
    i++;
    if (i > 100)
        break;
}memset(sendBuffer, 0, 1000);
memcpy(sendBuffer, &load, sizeof(load));
sendBuffer[sizeof(load)] = 0x00;LoadDouble loadtest;
memset(&load.container, 0, 100);
memcpy(&loadtest, sendBuffer, sizeof(loadtest));
cout << "loadtest.length:" << loadtest.length << endl;sendto(sockClient, sendBuffer, sizeof(sendBuffer), 0, (SOCKADDR*)&local, len);cout << "Successfully Send!" << endl;system("pause");
fclose(stdout);
fclose(stdin);
int ret = FreeConsole();
if (ret == 0)
{
    MessageBox(_T("Failed Free!"));
}MessageBox(_T("Successfully Send!"));

解决方案 »

  1.   

    找到答案了,在程序中我需要给 load.container[i]输入double类型的数据,我一般是以非法字符来结束输入的,这就破坏了cin的状态,下一次在进入窗口的时候,cin>> 的返回值即为false就不会进行输入了
      

  2.   

    乍看起来c++的cin、cout、ifstream、ofstream、istringstream、ostringstream在输入、输出上比c的scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf简单,不用格式控制符!
    但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。
    摒弃cin、cout、ifstream、ofstream、istringstream、ostringstream!
    使用scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf。