Combine all elements in vector into a new string MFC VC++ - vector

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.

Related

Sort QList<SerialPortinfo> [duplicate]

I have the following datastructure.
QList<QVariant> fieldsList
How can I sort this list? This list contains strings. I want to sort the fieldList alphabetically?
In Qt5, it seems qSort is deprecated. It's recommended to use:
#include <algorithm>
QList<QVariant> fieldsList;
std::sort(fieldsList.begin(), fieldsList.end());
Reference: site
I would do sorting in the following way:
// Compare two variants.
bool variantLessThan(const QVariant &v1, const QVariant &v2)
{
return v1.toString() < v2.toString();
}
int doComparison()
{
[..]
QList<QVariant> fieldsList;
// Add items to fieldsList.
qSort(fieldsList.begin(), fieldsList.end(), variantLessThan);
}
Update:
in QT5 the qSort obsoleted. But it is still available to support old source codes. It is highly recommended to use std::sort instead of that in new codes.
int n;
int i;
for (n=0; n < fieldsList.count(); n++)
{
for (i=n+1; i < fieldsList.count(); i++)
{
QString valorN=fieldsList.at(n).field();
QString valorI=fieldsList.at(i).field();
if (valorN.toUpper() > valorI.toUpper())
{
fieldsList.move(i, n);
n=0;
}
}
}

How to sort QList<QVariant> in Qt?

I have the following datastructure.
QList<QVariant> fieldsList
How can I sort this list? This list contains strings. I want to sort the fieldList alphabetically?
In Qt5, it seems qSort is deprecated. It's recommended to use:
#include <algorithm>
QList<QVariant> fieldsList;
std::sort(fieldsList.begin(), fieldsList.end());
Reference: site
I would do sorting in the following way:
// Compare two variants.
bool variantLessThan(const QVariant &v1, const QVariant &v2)
{
return v1.toString() < v2.toString();
}
int doComparison()
{
[..]
QList<QVariant> fieldsList;
// Add items to fieldsList.
qSort(fieldsList.begin(), fieldsList.end(), variantLessThan);
}
Update:
in QT5 the qSort obsoleted. But it is still available to support old source codes. It is highly recommended to use std::sort instead of that in new codes.
int n;
int i;
for (n=0; n < fieldsList.count(); n++)
{
for (i=n+1; i < fieldsList.count(); i++)
{
QString valorN=fieldsList.at(n).field();
QString valorI=fieldsList.at(i).field();
if (valorN.toUpper() > valorI.toUpper())
{
fieldsList.move(i, n);
n=0;
}
}
}

Why can't I use the -> operator for a struct pointer in main?

I thought that the general rule of thumb was that the -> operator was used for accessing members of struct pointers, and the . operator was used for accessing members of an actual struct. In my code, I thought I created a struct pointer, but I ended up still having to use the . operator. Can someone explain why?
typedef struct Robot
{
char **brain;
int size;
} Robot;
int main(void)
{
char buffer[100];
Robot *dalek = malloc(sizeof(Robot)*2);
for(i = 0; i < 2; i++)
dalek[i].brain = malloc(sizeof(char*) * 3);
for(i = 0; i < 3; i++)
{
scanf("%s", buffer);
dalek[0].brain[i] = malloc(sizeof(char) * strlen(buffer));
strcpy(dalek[0].brain[i], buffer);
}
}
dalek is a pointer, and dalek[i] is equivalent to *(dalek + i), i.e. it dereferences. If you want to use the arrow, say (dalek + i)->brain etc.
dalek[i] is defined as *(dalek+i). So when you do dalek[i]->brain you are really doing *(*(dalek+i)).brain, dereferencing a single pointer twice. If you really want to use the -> operator, you could use (dalek+i)->brain.

Search QString character by character

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();
}

Printing the contents of an array to a file

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;
}

Resources