I wrote a simple program to grab stock prices from yahoo finance. The loop that reads the data was truncating early (and ending about where the data from the website shows as opposed to the full download to the correct date for the excell file). So I put in a cout command in the loop to try to debug and voila, it worked correctly!
So why does using the cout function alter the program function? Any ideas? Below is the code. (I found two related posts, but still cant figure it out, e.g. "Can cout alter variables somehow?" and "Weird Error in C++ Program: Removing Printout Breaks Program")
#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;
}