int b=0;
QVector<int> z(5);
for(int i=0;i<5;i++)
z.push_back(i);
for(int i=0;i<z.size();i++)
{
b=z.at(i);
QString str=QString::number(b);
ui->mbox->setText(str);
}
I wrote this code to print a vector in plain text but it just print first row I want to print
whole vector
not:mbox is a plain textedit
now there is another problem
QVector<int> z(5);
for(int i=0;i<5;i++)
z.push_back(i);
QString str;
for (int i = 0; i < z.size(); ++i)
{
if (i > 0)
str += " ";
str += QString::number(z[i]);
}
ui->mbox->setText(str);
}
in first for loop when I wrote z.size() I get Qt has caught an exception thrown from an event handler. Throwing
exceptions from an event handler is not supported in Qt. You must
reimplement QApplication::notify() and catch all exceptions there.
and also in second for when I wrote z.size I get 10 output but size of z is 5 as you can see .what is wrog
first 5 output is 0 and then rest is normal like 0 1 2 3 4
but I should have 5 output am I wrong
You are overwriting the text for every item in the vector. Construct a QString from the values like this:
QString str;
for (int i = 0; i < z.size(); ++i)
{
if (i > 0)
str += " ";
str += QString::number(z[i]);
}
ui->mbox->setText(str);
Related
I'm trying to combine all the elements inside a vector as a new string but I can't get the example how to do this. Most of the examples are concatenating between vectors and also in C++ std::cout. I'm not sure how to do it in MFC VC++.
Let's say I have a vector (in CString) with the elements I am a naughty boy. How can I combine them and saved them as a
CString str;
str = "I am a naughty boy"
Edited:
struct REVLISTDATA {
CString str_;
REVLISTDATA(CString str_element) : str_(str_element) {}
};
std::vector<REVLISTDATA> vec;
If I am well understood your request, here is an approach:
for (size_t i = 0; i < vec.size(); ++i)
{
str.AppendFormat(vec.at(i));
if (i < vec.size() - 1)
str.AppendFormat(_T(" ")); // spaces between words
}
presuming that your vec is std::vector<CString>
Edit: So, instead of str.AppendFormat(vec.at(i)); you should use str.AppendFormat(vec.at(i).str_);
Later edit: I have tried the following code and work ok:
struct REVLISTDATA
{
CString str_;
REVLISTDATA(CString str_element) : str_(str_element) {}
};
std::vector<REVLISTDATA> vec;
vec.push_back(REVLISTDATA("I"));
vec.push_back(REVLISTDATA("am"));
vec.push_back(REVLISTDATA("a"));
vec.push_back(REVLISTDATA("naughty"));
vec.push_back(REVLISTDATA("boy"));
CString str;
for (size_t i = 0; i < vec.size(); ++i)
{
str.AppendFormat(vec.at(i).str_);
if (i < vec.size() - 1)
str.AppendFormat(_T(" ")); // spaces between words
}
So, I guess you exception is coming from other way.
I have made a program for my Arduino which will sort an array of fifty random numbers in ascending or descending order, I think I have got it all right, but when I run it I get an error message "expected unqualified-id before 'for' ".
int array [50];
int i = 0;
void setup() {
Serial.begin(9600); // Load Serial Port
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println ("Position " + array[i]);
delay (2000);
}
for (i <= 50) { <-----*Here is where the error highlights*--->
int n = random (251); // Random number from 0 to 250
array[i] = n;
i++;
}
// Bubble sort function
void sort (int a[], int size) {
for(int i=0; i<(size-1); i++) {
for(int o=0; o<(size-(i+1)); o++) {
if(a[o] > a[o+1]) {
int t = a[o];
a[o] = a[o+1];
a[o+1] = t;
}
}
}
}
I have annotated where the error is shown. I need to get past this to test my code, I have no clue on how to fix it!
You have written it wrong. There is pseudocode of for loop:
for(datatype variableName = initialValue; condition; operation){
//your in loop code
}
//Code wich will be executed after end of for loop above
In your case it will look like this:
for(int i = 0; i < 50 ; i++){
int n = random (251); // Random number from 0 to 250
array[i] = n;
}
Another thing is, that you are trying to iterate the array. The first index is 0. It means the last index is 49 not 50. If you try to access 50th index it will crash your program.
Last thing is, that the for loop we are talking about is out of any method. It will never be executed.
The for loop requires three parts to its parameters:
A variable to count iterations
A condition that must be true to continure
A increment factor
Each part should be separated by a semicolon
So your for loop should start out like this:
for(int i = 0;i <= 50; i++){
//code here
}
Official arduino For Loop Reference
i have table widget with specific row and column ,
my function is as follow
get value from the first column and second column
compare between them and return result in the third column
Ex: first column :1 2 3 Second column 2 2 3 Result column No Yes Yes
I make sure that my code work by using the qDebug, however when I compile and run it the mainwindow stopped and crash.
I use for loop to go throw all rows for(int row=0;rowtableWidget->rowCount();row++)
I think this line rowtableWidget->rowCount() coz when it read empty cells the app Freeze and stop working .
how can I void that to happen
void MainWindow::GenerateRes() {
QString Result;
for(int row = 0; row < ui->tableWidget->rowCount(); row++) {
QString R1 = ui->tableWidget->item(row, 0)->text();
QString R2 = ui->tableWidget->item(row, 1)->text();
if(R1 == R2) {
Result = "P" ;
} else {
Result = "F" ;
}
QTableWidgetItem *Item = new QTableWidgetItem(Result);
ui->tableWidget->setItem(row, 2, Item);
qDebug() << Item;
}
}
To check whether the cell(i,j) in QTableWidget is empty or not, use isNull() or isEmpty().
Example:
for(int i=0; i < ui->tableWidget->rowCount(); i++)
{
for(int j=0; j < ui->tableWidget->columnCount(); j++)
{
bool flag = ui->tableWidget->item(i,j)->text().isNull();
if (!flag) /* the cell is not empty */
{
// do stuff
}
else /* the cell is empty */
{
// do stuff
}
}
}
maybe you should check the values returned from tableWidget::item(), because the functions can return 0 if no item is asigned to the provided coordinates, and in that case you're trying to call a method (QTableWidgetItem::text()) on a zero pointer.
Try something like:
QString R1;
QTableWidgetItem *item1(ui->tableWidget->item(row,0));
if (item1) {
R1 = item1->text();
}
// and so on...
Your code looks strange anyway, the 5th line (ui->tableWidget->rowCount()) doesn't make sense, you shouldn't be able to compile that (at least you're missing a semicolon).
I'm trying to parse a QString character by character with a while loop, but I can't figure out how to parse an individual character to char type. Here's my code, I know it's not optimal:
QString temp = (QString)t[0];
int i = 1;
while (t[i] != " ");
{
temp.append(t[i]);
i += 1;
}
I've seen the casting with toLocal8bit function, but whatever I try I just cannot adapt it to my code.
Qt Creator shows this error:
error: conversion from 'const char [2]' to 'QChar' is ambiguous
in line with the while function call
You can use C++ 11 range based for loop
for (auto chr : text)
{
if (!chr.isDigit()) // for exmpl.
return false;
}
Why don't you try that :
QString test = "test";
for(int i = 0; i< test.length(); i++)
{
if (test.at(i) != " ")
test.at(i).toLatin1();
}
Pointer related question. I'm going through some example code that currently reads in data from a file called dataFile into a buffer. The reading is done inside a loop as follows:
unsigned char* buffer = (unsigned char*)malloc(1024*768*);
fread(buffer,1,1024*768,dataFile);
redPointer = buffer;
bluePointer = buffer+1024;
greenPointer = buffer+768;
Now, I want to try and write the entire contents of the array buffer to a file, so that I can save just those discrete images (and not have a large file). However, I am not entirely sure how to go about doing this.
I was trying to cout statements, however I get a print-out of garbage characters on the console and also a beep from the PC. So then I end my program.
Is there an alternative method other than this:
for (int i=0; i < (1024*768); i++) {
fprintf(myFile, "%6.4f , ", buffer[i]);
}
By declaring your buffer as a char*, any pointer arithmatic or array indexes will use sizeof(char) to calculate the offset. A char is 1 byte (8 bits).
I'm not sure what you are trying to do with the data in your buffer. Here are some ideas:
Print the value of each byte in decimal, encoded as ASCII text:
for (int i=0; i < (1024*768); i++) {
fprintf(myFile, "%d , ", buffer[i]);
}
Print the value of each byte in hexadecimal, encoded in ASCII text:
for (int i=0; i < (1024*768); i++) {
fprintf(myFile, "%x , ", buffer[i]);
}
Print the value of each floating point number, in decimal, encoded in ASCII text (I think my calculation of the array index is correct to process adjacent non-overlapping memory locations for each float):
for (int i=0; i < (1024*768); i += sizeof(float)) {
fprintf(myFile, "%6.4f , ", buffer[i]);
}
Split the buffer into three files, each one from a non-overlapping section of the buffer:
fwrite(redPointer, sizeof(char), 768, file1);
fwrite(greenPointer, sizeof(char), 1024-768, file2);
fwrite(bluePointer, sizeof(char), (1024*768)-1024, file3);
Reference for fwrite. Note that for the count parameter I simply hard-coded the offsets that you had hard-coded in your question. One could also subtract certain of the pointers to calculate the number of bytes in each region. Note also that the contents of these three files will only be sensible if those are sensibly independent sections of the original data.
Maybe this gives you some ideas.
Updated: so I created a complete program to compile and test the formatting behavior. This only prints the first 20 items from the buffer. It compiles (with gcc -std=c99) and runs. I created the file /tmp/data using ghex and simply filled in some random data.
#include <stdlib.h>
#include <stdio.h>
int main()
{
FILE* dataFile = fopen("/tmp/data", "rb");
if (dataFile == NULL)
{
printf("fopen() failed");
return -2;
}
unsigned char* buffer = (unsigned char*)malloc(1024*768);
if (buffer == NULL)
{
printf("malloc failed");
return -1;
}
const int bytesRead = fread(buffer,1,1024*768,dataFile);
printf("fread() read %d bytes\n", bytesRead);
// release file handle
fclose(dataFile); dataFile = NULL;
printf("\nDecimal:\n");
for (int i=0; i < (1024*768); i++) {
printf("%hd , ", buffer[i]);
if (i > 20) { break; }
}
printf("\n");
printf("\nHexadecimal:\n");
for (int i=0; i < (1024*768); i++) {
printf("%#0hx , ", buffer[i]);
if (i > 20) { break; }
}
printf("\n");
printf("\nFloat:\n");
for (int i=0; i < (1024*768); i += sizeof(float)) {
printf("%6.4f , ", (float)buffer[i]);
if (i > 20) { break; }
}
printf("\n");
return 0;
}