gpt4 book ai didi

c++ - Cout 修复了 C++ 程序中的错误,但为什么呢?

转载 作者:太空狗 更新时间:2023-10-29 23:31:33 27 4
gpt4 key购买 nike

我写了一个简单的程序来从雅虎财经获取股票价格。读取数据的循环被提前截断(并结束于网站数据显示的位置,而不是完整下载到 excel 文件的正确日期)。所以我在循环中放入了一个 cout 命令来尝试调试,瞧,它工作正常!

那么为什么使用 cout 函数会改变程序功能?有任何想法吗?下面是代码。 (我找到了两个相关的帖子,但仍然无法弄清楚,例如“cout 能以某种方式改变变量吗?”和“C++ 程序中的奇怪错误:删除打印输出中断程序”)

#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <windows.h>
#include <wininet.h>

using namespace std;
int main()
{
HINTERNET hOpen, hURL;
LPCWSTR NameProgram = L"Webreader"; // LPCWSTR == Long Pointer to Const Wide String
LPCWSTR Website;
char file[101];
int i;
string filename;
unsigned long read;

filename = "data.txt";
ofstream myFile(filename);
if (! myFile)
{
cout < "Error opening file\n";
}
if ( !(hOpen = InternetOpen(NameProgram, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 )))
{
cerr << "Error in opening internet" << endl;
return 0;
}
Website = L"http://ichart.finance.yahoo.com/table.csv?s=MSFT&a=00&b=1&c=2009&d=09&e=22&f=2010&g=d&ignore=.csv";
hURL = InternetOpenUrl( hOpen, Website, NULL, 0, 0, 0 ); //Need to open the URL
InternetReadFile(hURL, file, 100, &read);
file[read] = '\0';
myFile << file;
while (read == 100)
{
InternetReadFile(hURL, file, 100, &read);
file[read] = '\0';
myFile << file;
cout << file; //If I take this line out, the function terminates early.
}
myFile << file;
InternetCloseHandle(hURL);
myFile.close();
return 0;
}

最佳答案

你拥有的是一个“Heisenbug”,当你试图找到它时它就会消失。别搞错了,问题仍然存在,您确实需要找到它。

您应该做的第一事情是检查InternetReadFile 的返回码。

此外,您不应该假设成功读取将返回完整的 100 个字节,即使还有更多字节。 doco状态:

To ensure all data is retrieved, an application must continue to call the InternetReadFile function until the function returns TRUE and the lpdwNumberOfBytesRead parameter equals zero.

: : :

Also, converted lines might not completely fill the buffer, so InternetReadFile can return with less data in lpBuffer than requested.

换句话说,我要补充:

BOOL rc;

并改变你的两个:

InternetReadFile(hURL, file, 100, &read);

声明:

rc = InternetReadFile(hURL, file, 100, &read);

然后你的循环变成:

while ((!rc) || (read > 0))   // I *think* that's right.

关于c++ - Cout 修复了 C++ 程序中的错误,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3993535/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com