Can someone tell me how I can display a message box in C that can print variables?
I mean like this:
#include <stdio.h>
#include <windows.h>
main()
{
int x = 5;
MessageBox(0, "Variable x is equal to %d", "Variable", 0);
/* Where do I specify the variable so that 5 will display?*/
getch();
}
To look like this:
Variable
Variable x is equal to 5.
Thanks in advance!
MessageBox itself doen't support printf like formatting. You'll have to use snprintf for that:
char buf[1024];
snprintf(buf, 1024, "Variable x is equal to %d", x);
MessageBox(0, buf, "Variable", 0);
I want to debug multiple variables of type integer or string as a list within a single MessageBox so that I do not have to press the button repeatedly. This extension to #Bart's answer does it:
#include <windows.h>
#include <stdio.h>
#include <string.h>
char debugMsg [1024] = ""; // buffer for debug message
void debugStr (char* varName, char* var) {
snprintf (debugMsg, sizeof (debugMsg), "%s%s=%s\n", debugMsg,
varName, var);}
void debugInt (char* varName, int var) {
snprintf (debugMsg, sizeof (debugMsg), "%s%s=%d\n", debugMsg,
varName, var);}
void main () {
char myStrA [] = "letter A", myStrZ [] = "letter Z";
int myIntA = 65, myIntZ = 90;
// Concat debug message from multiple vars of type integer or string:
debugStr ("myStrA", myStrA);
debugInt ("myIntA", myIntA);
debugStr ("myStrZ", myStrZ);
debugInt ("myIntZ", myIntZ);
MessageBox (NULL, debugMsg, "Debug", MB_OK); // returns this list:
// myStrA=letter A
// myIntA=65
// myStrZ=letter Z
// myIntZ=90
memset (debugMsg, 0, sizeof debugMsg); // clear debug message
}
Related
This is my code:
#include <stdio.h>
#include <string.h>
#define VERSION "2.16.0.0"
int main ()
{
//char buf[] ="2.16.0.0";
int i = 0;
int j ;
char letter[8];
//char a[] = VERSION;
for(i=0;i<8;i++)
{
letter[i] = VERSION[i];
}
char *array;
char* copy = letter ;
while ((array = strtok_r(copy, ".", ©)))
printf("%s\n", array);
printf("%s", array);
}
I split the macro to 2 16 0 0.
Now, I want to format it to 02 16 00 00. How do I do it?
I tried using sprintf() function to format the array but that didn't work out, any other way?
Your program can be simplified in several ways (see below) and I have to point out at least one significant error since the copy of the string in letter does not include the terminating 0.
About how to print, as I understand you would like to print the numerical entries with 2 digits. One method to do that is to convert them to integers and format the output using the printf formatting options:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define VERSION "2.16.0.0"
int main ()
{
char *element;
char copy[] = VERSION;
element = strtok(copy, ".");
while (element != NULL)
{
printf("%02d ", atoi(element));
element = strtok(NULL, ".");
}
}
I'm trying to pass mixed types to printf(). In the actual code (at the bottom) I also pass the format placeholder so that printf() knows how to format.
While accidently using these void* pointers directly as call by values, I discovered that my code was not working as expected.
So I created a test program, searched and poked around until I came up with this solution.
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void test1(void* a) {
printf("value: %d\n", *(int*)a);
}
void test2(void* a) {
printf("value: %f\n", *(float*)a);
}
int main(int argc, char** argv) {
int* aip = &(int){1};
test1(aip);
int ai = 1;
test1(&ai);
float af = 1.75;
test2(&af);
return 0;
}
But I don't want hardcoded *(int*) or *(float*) dereferencing and casting but actually write something like this:
void test(void* a) {
printf("value: %VARIES\n", a);
}
VARIES is passed into test() and concatenated into the final formatter string.
The actual function looks like this:
void fn(void* value, char* fmtChar) {
char fmtHelper[50];
// fill fmtChar in formatter string's %s placeholder
snprintf(fmtHelper, sizeof(fmtHelper), "value : %s\n", fmtChar);
// actually print value varying argument
printf(fmtHelper, value);
}
My curent workaround uses switch/case statements and determines the casting and formatter placeholders programmatically.
If you're targeting current C (C11), you can use a type-generic expression with a macro to make a type-generic function:
#include <stdio.h>
void print_int(int x) {
printf("an int: %d\n", x);
}
void print_double(double x) {
printf("a double: %f\n", x);
}
#define print(X) _Generic((X), \
float: print_double, \
double: print_double, \
default: print_int \
)(X)
int main(void) {
print(1); // an int: 1
print(1.0); // a double: 1.00000
}
This solution uses vprintf and va_list macros, so they're resolved during the preprocessing of the source.
#include <stdio.h>
#include <stdarg.h>
void print(char* msg, char* fmtChars, ...) {
// format string and write the result to fmtHelper
// %s is replaced with the value placeholder types
// (fixed length for simplicity)
char fmtHelper[50];
snprintf(fmtHelper, sizeof(fmtHelper), "%s; value 1: %s, value 2: %s\n", msg, fmtChars, fmtChars);
va_list args;
// treat all parameters _after_ this named as variable arg
va_start(args, fmtChars);
vprintf(fmtHelper, args);
va_end(args);
}
int main(void) {
char* msg = "Test";
int in1 = 1;
int in2 = 2;
float fl1 = 4.21;
float fl2 = 5.89;
print(msg, "%f", fl1, fl2);
print(msg, "%d", in1, in2);
}
This was a hint #rici gave in the comments section.
in this code, I am creating two threads (joystick and motor). The intention of the joystick thread is to ask the user to input a certain speed integer value (for eg. 200). From my understanding, this integer value must be converted to a string in-order for the motor thread to receive this string value and convert it back to an integer value, before passing it into my application.
The result of the compiled code in GCC is my motor application receives a speed of zero despite a user input of any other numbers, and hence, it is not moving. May I know if I had done the conversion from integer to string or vice versa wrongly?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_LEN 128
//char n[1024];
pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
int string_read=FALSE;
pthread_cond_t cond;
void * joystick()
{
while (1)
{
int s;
char str[7];
while(string_read);
pthread_mutex_lock(&lock);
printf("Enter speed: ");
scanf("%d", &s);
snprintf(str, 7, "%d", s); //Convert int to string: itoa or snprintf
//itoa (j, n, 10);
//printf ("Decimal: %s\n", n);
string_read=TRUE;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
}
void * motor()
{
while (1)
{
pthread_mutex_lock(&lock);
while (!string_read)
pthread_cond_wait(&cond,&lock);
char *s = "s"; //How to receive the string value from joystick()?
int val = atoi(s);
printf ("Integer value of string is %d\n", val);
char buffer [MAX_LEN];
system ("./SmcCmd --resume"); //WORKING
snprintf (buffer, MAX_LEN, "./SmcCmd --speed %d", val); //WORKING
int status = system(buffer); //WORKING
string_read=FALSE;
pthread_mutex_unlock(&lock);
}
}
int main ()
{
int status;
pthread_t tj, tm;
pthread_create(&tj, NULL, joystick, NULL);
pthread_create(&tm, NULL, motor, NULL);
pthread_join(tj, NULL);
pthread_join(tm, NULL);
return 0;
}
unsigned int H_SMPTR_LEN = 0;
#ifndef _RSZLEN
#define _RSZLEN(nvalue) H_SMPTR_LEN = nvalue;
#endif
//Smart pointer structure with built-in size
typedef struct SMPTR
{
void *MBLOC;
const unsigned int *length;
unsigned int bloc_size;
} SMPTR;
#ifndef _SMPTR
#define _SMPTR(SMPTR, var_sz, v_num) SMPTR.MBLOC = malloc(var_sz * v_num); SMPTR.bloc_size = v_num * var_sz; _RSZLEN(v_num); SMPTR.length = &H_SMPTR_LEN;
#endif
I wrote this code to experiment with const * to an integer. When I run and implement the code above like so:
#include <stdio.h>
#include <stdlib.h>
#include "cdebug.h"
int main(int argc, char **argv)
{
SMPTR s;
_SMPTR(s, sizeof(char), 50);
fprintf(stdout, "%i\n", s.bloc_size);
fprintf(stdout, "%i\n", s.length);
fprintf(stdout, "%i\n", H_SMPTR_LEN);
fprintf(stdout, "%s", "Done!\n");
return 0;
}
The second output statement is a screwy output result. In theory the second output result should match the third, because the SMPTR.length member points to H_SMPTR_LEN.
The first bit of code is part of my header called "cdebug.h", which is included in main(). I am wondering if I am using const pointers correctly here. The idea here is to create a structure whose members can only be modified in a controlled environment, i.e. a method I write.
#include <stdio.h>
#define stringify(s) tostring(s)
#define tostring(s) #s
#define MAX_VALUE 65536
#define NUM 64 * 1024
enum {
MIN_VALUE = 1024,
};
int main(int argc, char *argv[])
{
const char *max_str = stringify(MAX_VALUE);
const char *min_str = stringify(MIN_VALUE);
printf("max = %s, min = %s\n", max_str, min_str);
return 0;
}
The output is "max = 65536, min = MIN_VALUE num = 1024 * 64"
Experts, how can I modify my code to output like this:
max = 65536, min = 1024 num = 65536
Thanks .
MIN_VALUE is a number. Why do you need to stringify it?
Just use:
printf("%d\n", MIN_VALUE);
I think you're better off using a function instead of a macro for this, the reason being that macros are only expanded even before compile time, let alone runtime.
consider this example:
#define stringify(V) #V
#include <stdio.h>
int main()
{
int x = 5;
const char *str = stringify(x);
printf("%s\n", str);
}
after the preprocessor has done it's work, the code will look like this:
#include <stdio.h>
int main()
{
int x = 5;
const char *str = "x";
printf("%s\n", str);
}
that is because all the preprocessor directive # does, is wrap the given parameter in quotes.
If you want to have an int to string behaviour that works on constants, enums (cast to int) and integer variables, you could use sprintf:
#include <stdio.h>
#include <stdlib.h>
char *stringify(int x)
{
/* get the length of the required buffer */
int len = snprintf(0, 0, "%i", x);
/* allocate memory */
char *res = malloc(sizeof(char) * (len + 1));
/* handle allocation failure */
if(!res)
return 0;
/* convert the int to string */
snprintf(res, len + 1, "%i", x);
/* return the result */
return res;
}
int main()
{
int x = 5;
char *str = stringify(x);
printf("%s\n", str);
/* we free the memory allocated by malloc */
free(str);
}
this would be one way you could to this in C. If you want to know more about the functions I used, have a look at:
http://www.manpagez.com/man/3/vsnprintf/
http://www.manpagez.com/man/3/malloc/
#define statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).
Since stringify(s) is #defined, the preprocessor faithfully does it job.
stringify(MAX_VALUE) decays to stringify(65536) since MAX_VALUE is #defined to 65536, also known at preprocessing.
But Enumerations are part of the C language itself and not known at preprocessing,
So, stringify(MIN_VALUE) retains as stringify(MIN_VALUE) and hence toString(MIN_VALUE)
To do integer arithmetic or to print
num = 65536
"yes", there is a way to make the preprocessor perform integer arithmetic, which is to use it in a preprocessor condition.
#if 1024*64 == 65536
printf("num=65536\n");
#endif