字符串'G'未显示

时间:2013-11-17 10:52:25

标签: c++

所以这是client.cpp文件。所以有什么问题?我声明这个字符串'G',我输入昵称然后在这里'cout&lt;&lt; G <&lt; “:”&lt;&lt; sbuffer.Message&lt;

P.S。:我认为我不需要发布server.cpp文件,是吗?

    #pragma comment(lib, "Ws2_32.lib")

#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;


SOCKADDR_IN addr;

SOCKET sConnect;

string G;

struct Buffer
{
    int ID;
    char Message[256];
};

int ClientThread()

{         缓冲sbuffer;

char buffer[sizeof(sbuffer)] = {0};

for(;; Sleep(10))
{
    if(recv(sConnect, buffer, sizeof(sbuffer), NULL))
    {
        memcpy(&sbuffer, buffer, sizeof(sbuffer));
        cout << G << ":" << sbuffer.Message <<endl;
    }
}

return 0;

}

int main()

{     系统( “CLS”);

int RetVal = 0;

WSAData wsaData;
WORD DllVersion = MAKEWORD(2,1);
RetVal = WSAStartup(DllVersion, &wsaData);
if(RetVal != 0)
{
    MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
    exit(1);
}

sConnect = socket(AF_INET, SOCK_STREAM, NULL);

addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port        = htons(1234);
addr.sin_family      = AF_INET;

cout << "Connect to Masterserver? [ENTER]" <<endl;
getchar();
RetVal = connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));

if(RetVal != 0)
{
    MessageBoxA(NULL, "Could not connect to server", "Error", MB_OK | MB_ICONERROR);
    main();
}
else
{
    string G;
    cout << "Nickname: " << endl;
    cin >> G;

    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) ClientThread, NULL, NULL, NULL);

    for(;; Sleep(10))
    {
        char* buffer = new char[256];
        ZeroMemory(buffer, 256);

        cin >> buffer;
        getchar();

        send(sConnect, buffer, 256, NULL);
    }
}

return 0;

}

2 个答案:

答案 0 :(得分:5)

您在顶部的全局范围中声明的string Gstring G范围内声明的main遮蔽,因此您读入的ClientThread不可用到{{1}}方法。删除主范围内的声明。

答案 1 :(得分:4)

如果那是同一个文件,那么当你只应该做一次时,你就会宣告G两次。

// string G;
cout << "Nickname: " << endl;
cin >> G;