Reputation: 3
I have been writing a program in c++ that will take in some data from a python program I wrote, I used python because it's much quicker to format the data for use in c++ utilizing the >> operator from a istringstream variable.
My python program had to merge together two separate files, merging them by sorting via timestamp then print out the resulting sorted array. I used output redirection to capture the printed output into a file. I would then operate on that file using the c++ program.
RC 1548997200000 apple 4
RQ 1549003500000 banana 4
The idea here being that I would utilize this formatted data as shown above in C++.
I used something like this:
std::string name, type, line;
int score, timeStamp;
while (std::getline(std::cin, line)) {
std::istringstream SS(line);
SS >> type >> timeStamp >> name >> score;
When running through this code in the visual studio debugger I was finding that the type string variable was correctly taking in its value such as "RC" and "RQ", but the timeStamp variable was not receiving its input correctly, nor was name or score. The SS istringstream was correctly representing the redirected input, and the line string variable was also correct.
I did some basic testing and took out the timestamp and the two spaces before and after it, then input a space a zero and a final space so that the first line was this: "RC 0 apple 4" and to my surprise all my variables were correctly receiving the input they should be.
All this leads me to believe I have an encoding error in my files. I was doing this without the timestamp merging and then this problem started happening once I began using timestamps.
Any help is appreciated.
Upvotes: 0
Views: 39
Reputation: 149
The problem comes from type of timeStamp. The time stamp has 13 digits, but int type in c++ can only store up to 10 digits. Try long long int instead.
Please see the questions What range of values can integer types store in C++ and C++ : storing a 13 digit number always fails for more details.
Someone else were working on similar problem and the code may give you more information: C++ Extract int from string using stringstream.
Upvotes: 0
Reputation: 211740
You're using millisecond timestamp values and these vastly exceed the bounds of what a normal int
can store. Consider using int64_t
or long long int
that will give you the required range.
One thing you should consider is using the existing std::cin
stream instead of reading out a line, converting that line to a stream, and then reading from that.
Upvotes: 1