我的控制台应用程序出了问题。我正在学习关于网络的某种教程,当我尝试在调试中运行时,我遇到了一个我从未见过的奇怪的运行时错误。
当我在主函数内的第一个新行上放置一个断点并通过Step Over(F10)执行代码时,visual studio执行前三行代码,包括WSAStartup(),然后突然到达acomment部分:
#include <winsock2.h>
#include <WS2tcpip.h>
#include <iostream>
#include "wsh_includes.h"
int main(int argc, const char* argv[])
{
//You have to make a call to WSAStartup() before doing anything else with the sockets library
//WSADATA wsaData; // if this doesn't work
WSAData wsaData; // then try this instead
wsh::errcheck(WSAStartup(MAKEWORD(2, 2), &wsaData), "WSAStartup failed");
//----------
//You also have to tell your compiler to link in the Winsock library, usually called
//wsock32.lib or winsock32.lib, or ws2_32.lib for Winsock 2.0
//----------
//you can't use close() to close a socket—you need to use closesocket()
//----------
//select() only works with socket descriptors, not file descriptors (like 0 for stdin).
//There is also a socket class that you can use, CSocket
//----------
int status;
addrinfo hints, *res, *p;
char ipstr[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof(hints)); //make sure it's empty
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM; //TCP stream sockets
status = getaddrinfo("www.example.net", NULL, &hints, &res);
wsh::errcheck(status, "getaddrinfo failed");
//servinfo now points to a linked list of 1 or more struct addrinfos
//... do everything until you don't need servinfo anymore ...
printf("IP addresses for %s:\n\n", argv[1]);
for (p = res; p != NULL; p = p->ai_next) {
void* addr;
char* ipver;
//get the pointer to the address itself
//different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) {
sockaddr_in* ipv4 = (sockaddr_in*)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
}
else {
sockaddr_in6* ipv6 = (sockaddr_in6*)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
//convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
printf(" %s: %s\n", ipver, ipstr);
}
std::cin.get();
freeaddrinfo(res); //free the linked list
//----------
//Finally, you need to call WSACleanup() when you're all through with the sockets library.
wsh::errcheck(WSACleanup(), "WSACleanup failed");
return 0;
}
当它到达时,它突然移动到评论部分中间的文件crtexe.c。 更具体地说,它跳转到:
#ifdef WPRFLAG
__winitenv = envp;
mainret = wmain(argc, argv, envp);
#else /* WPRFLAG */
__initenv = envp;
mainret = main(argc, argv, envp); //here
然后到:
#else /* !defined (_WINMAIN_) && defined (_CRT_APP) */
if ( !managedapp )
{
#ifndef _CRT_APP
exit(mainret); //here
我尝试删除所有注释,当我在调试中运行时,代码的行为会有所不同(但并不像预期的那样)。
这里究竟发生了什么,我该如何解决?
答案 0 :(得分:1)
这通常是由不匹配的行结尾引起的(某些行以CR / LF结尾,有些以CR或LF结尾),这导致IDE无法使代码编辑器和调试器保持同步。 / p>
VS经常识别这种情况,并显示一个对话框,询问您是否要规范化行结尾(有关详细信息,请参阅What does Visual Studio mean by normalizing line endings?)。
您可以使用文件 - &gt;高级保存选项菜单项自行解决此问题,并将行结尾设置为 Windows(CR LF)< /强>