QT Read file, convert to int and use as initial slider value - c++

I've made a horizontal slider, the value is being saved in a text file. After the app is closed slider resets to the initial value of "1". Using -
ui->horizontalSlider->setValue(read());
I want to read the value of the file using read() function and set it as the initial value for the slider which results in the value being restored / saved.
This is read(); function-
int read(){
std::fstream readfile;
readfile.open("bin\ram.dat");
std::string value;
readfile << value;
int value2 = atoi(value.c_str());
return value2;
}
After a lot of different variable types being used and few conversion it does not work.
Question- how to set the initial value of slider to int located in "bin\ram.dat"? I'm a beginner so any tips or clues are more than welcome. Thanks! (I've googled it before posting and found few codes which did not work here)

Related

How to have c++ webscraper scrape through html until it hits a float/int

I am trying to use a C++ scraper in my ui to cipher through WSJ stock information to get some balance sheet info back, I have it for where it searchers for specific text in the page source ie "Pe/Ratio" and then i manually counted how many chars are in between it and the actual number on the website.
Here is the picture of the code
// P/E Ratio
size_t indexpeRatio = html.find("P/E Ratio ") + 116;
string s_peRatio = html.substr(indexpeRatio, 5);
peRatio = stod(s_peRatio);
After manually doing that it simply stores the number and I output it to my UI. My Issue is that sometimes the number of characters in between change depending on which company i choose to evaluate. I am wondering if there is a way to use the .find() function to find the "Pe/Ratio" then output the next float/int,
here is what the html looks like on the site
As of right now sometimes my ui will output parts of the html due to having to use a fixed number of chars
this is an example of my ui output when giving a smaller company to evaluate
Do you all have any recommendations I can use to fix this issue? Thank you in advance!
You could iterate through the characters.
Say you have string html:
#include<ctype.h>
#include<string>
using namespace std;
int main(){
double peratio;
string html;
/*
This is where you do your HTML scraping logic
*/
size_t indexpeRatio=html.find("P/E Ratio");
peratio=find_ratios(html.substr(indexpeRatio,strlen(html)-indexpeRatio));
}
double find_ratios(string html){
int i=0;
std::string output;
bool wasInt=false,isInt=false;
while(html[i]!='\0'&&!wasInt){
if(isdigit(html[i]))
isInt=true;
if(isInt)
if(html[i]!='.'&&!isdigit(html[i])){
wasInt=true;
isInt=false;
}
else output+=html[i];
i++;
}
return stod(output);
}

C++ reading file into an object

So I'm trying trying read a file into several objects, and right now I'm practicing by trying to insert a single line into a single object. This the object class I'm trying to insert the file in:
Cust(string name, bool robber, int time, int items)
{
m_name = name;
m_robber = robber;
m_time = time;
m_items = items;
}
After reading the file, I try to insert them into the object and print the object to see if it successfully came out. I know the print function works just fine, so there's no reason to worry about that.
ifstream my_ifile(argv[3]);
string k_name;
bool k_robber;
int k_time;
int k_items;
my_ifile >> k_name;
my_ifile >> k_robber;
my_ifile >> k_time;
my_ifile >> k_items;
Cust k_customer(k_name, k_robber, k_time, k_items);
k_customer.print(cout);
The file I'm putting in has one line.
Robbie true 1 2
And the print function should print "Robbie robber 1 2". Instead this is the output I get:
shopper 638496768 32631
It starts with a space, it's set to shopper instead of robber, the numbers are incorrect, the name is omitted entirely and the file's contents are erased. Does anyone know why this is happening?
Also how would I read through two or more lines? I.e.
Robbie true 1 2
Shaun false 3 4
Thanks for the help!

String to Integer Conversion in MFC [duplicate]

This question already has answers here:
Convert MFC CString to integer
(12 answers)
Closed 7 years ago.
I am just a beginner to MFC platform. I am just trying a simple pgm. Getting 2 numbers in 2 edit boxes and displaying the sum in the third edit box when a button is clicked.
This is my code:
void CMineDlg::OnEnChangeNumber1()
{
CString strNum1,strNum2;
m_Number1.GetWindowText(strNum1,10); //m_NUmber1 is variable to 1st edit box.
m_Number2.GetWindowText(strNum2,10); //m_Number2 is variable to 2nd edit box.
}
void CMineDlg::OnBnClickedSum()
{
m_Result=m_Number1+m_Number2;
}
I know I have to convert the strings to integer. But I have no idea how to do it. Pls Help.
You can use Class Wizard to add variables of integer type and associate them with edit boxes. Then, in OnEnChangeNumber1 event handler (or in OnBnClickedSum), you simply call UpdateData(TRUE); which causes those variables to update their values. After that, you can sum those integer variables.
Use
CString strNum = _T("11"); //CString variable
int num; //Integer Variable
_stscanf(strNum, _T("%d"), &num); //Conversion
Or
num = atoi((char*)(LPCTSTR)strNum);
The correct UNICODE compliant way of doing this:
CString str = _T("10");
int nVal = _ttoi(str);
__int64 = _ttoi64(str);

reading from a file and storing it in a structure(not properly reading the file)

The problem with my code is that in the while loop, the program is not properly reading the data in the file. If I were to output each individual member of the structure out of the while loop it would output stuff like zero, blank and even random numbers to different members of the structure. This also means that nothing is getting added to the vector because the vector size is zero.
Note 1-I'm using codeblocks as my IDE.
Note 2-The file that I'm using is an excel file. This means that I'm assuming that you've worked with excel files before and that you know that they're lined up in columns and rows. Also, I only want a certain amount of data going to each member in the structure.
Here's a very small sample from my input file.
EVENT_ID CZ_NAME_STR BEGIN_DATE BEGIN_TIME
9991511 MIAMI-DADE CO. 10/18/1955 800
9991516 MIAMI-DADE CO. 4/10/1956 1730
9991517 MIAMI-DADE CO. 4/10/1956 1730
Here's my code
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
// Structure.
struct Weather_Event
{
int eventID; // is the unique int id associated with the weather event.
string CZ_NAME; // is the location associated with the weather event.
char beginDate[11]; // is the date the event started.
char beginTime[5]; // is the time the event started.
string eventType; // is the type of weather event.
int deaths; // are the number of people killed by the weather.
int injuries; // are the number of people injured by the event.
int propertyDamage; /* is the $ worth of property damage caused
by the event. */
float beginLatitude; // is the starting latitude for the event.
float beginLongitude; // is the starting longitude for the event.
};
int main()
{
// Create an empty vector that will contain the structure.
vector<Weather_Event>weatherInformation(0);
Weather_Event data; /* Create an object to access each member in
the structure. */
// Declare an object and open the file.
ifstream weather("weatherdata.csv");
if(!weather) // Check to see if the file opens.
{
cerr << "Error, opening file. ";
exit(EXIT_FAILURE); // terminate the program early.
}
/* While you're not at the end of the file, keep reading each new
piece of data. */
while(weather >> data.eventID >> data.CZ_NAME >> data.beginDate
>> data.beginTime >> data.eventType >> data.deaths
>> data.injuries >> data.propertyDamage >> data.beginLatitude
>> data.beginLongitude)
{
/* Add all the data that was added to each member of the
structure, into the vector. */
weatherInformation.push_back(data);
}
weather.close();
// Next display the result
for(size_t i=0; i<weatherInformation.size(); i++)
{
cout << "EventID: " << weatherInformation[i].eventID << endl;
}
return 0;
}
For starters, the format of the input doesn't seem to contain all the fields being read. That is, the input contains columns for event ID, name, begin data, and begin time but the code also reads event type, deaths, injuries, property damage, latitude, and longitude. Once this problem is address, you'll run into different other problems, though:
The first line doesn't match the format you are trying to read at all. You'll need to ignore it, e.g., using weather.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
The formatted input operator for string reads a single word. However, your name consists of multiple words, i.e., only the first of these words is read. I don't know if your file contains a suitable separators (e.g. tab characters '\t') you could use to delimit the name or if the name as a fixed length or something. You'll need something to tell the stream where to stop reading the name.
When reading into a char array using the formatted input operators, you should set up a limit for the characters to be read to avoid an overflow: if you don't set up a limit, as many characters as matching the format will be read! That is, you want to read the beginDate and the beginTime using something like this:
weather >> std::setw(sizeof(data.beginDate)) >> data.beginDate
>> std::setw(sizeof(data.beginTime)) >> data.beginTime;
Setting the width limits the amount of data being read. If there are more characters the input will fail rather than overflowing the buffer (if I recall correctly).
These are the problems I spotted based on the code and data you posted.

Set widget label text in a thread in Qt

I'm new in Qt and I'm really stuck with threading. I know that this is question answered many times, but I can't figure out how to solve my problem. I have widget application with several labels and I have a class that reads data from serial port. I need to read data continuously and show them in labels. I've found many different answers about threading in Qt, but I cant get any of them to work. Can anyone point me to the right direction.
This code shows approximately what I want to achieve:
serial port class:
SerialPort *port;
int value1;
int value2;
int value3;
void Port::ReadData()
{
// First I send data to serial port as a QByteArray
QByteArray data = port.readAll();
value1 = data[0];
value2 = data[1];
value3 = data[3];
// Of course it's not really like this but I process data and assign them to
variables
}
Variables value1, value2 and value3 are public and I use label1->setText(portClass.value1) to show data. When I use this with a button click ti works but I want to close it to a loop and read data continuously.
labels have slots you can call from any thread using invokeMethod:
QMetaObject::invokeMethod (label1, "setText",
Q_ARG(QString,data[0]);
QMetaObject::invokeMethod (label2, "setText",
Q_ARG(QString,data[1]);
QMetaObject::invokeMethod (label3, "setText",
Q_ARG(QString,data[2]);