char a[200] = { 0 };
char tst[20] = "aaaa 123\n";
int i;
sscanf_s(tst, "%s %d",a, &i);
printf("reasult:%s %d", a,i);
No matter I use char tst[20] = "aaaa 123\n"; or char* tst = "aaaa 123\n";,
it always shows access violation.
I need to seperate a string an integer from a string. But why this happens ?
sscanf_s expects two arguments for %c, %s and %[, the second being the size of the buffer passed. The following should work:
sscanf_s(tst, "%s %d", a, sizeof(a), &i);
Related
const char* val1 = advertisedDevice.getAddress().toString().c_str();
Serial.printf("Advertised Device: %s \n", val1);
This code is used to retrieve the MAC address of a BLE device.
The output of val1 on the serial monitor is:
Advertised Device: 45:89:a2:d8:74:65
But when I try to output val1 individually the system crashes. The code is shown below. Why is this?
Serial.printf("Val is : %s", val1[0]);
I should expect the serial monitor is print out
Val is : 4
I am also trying to store val1 is a string array, so for example
pseudo-code
String arr[50];
loop{
const char* val1 = advertisedDevice.getAddress().toString().c_str();
Serial.printf("Advertised Device: %s \n", val1);
arr[i] = val1[0]+val1[1]+val1[2]+....+val1[18]
i++;
}
I want to store it in a single array because I then upload it to a database. I cant do this if its in the form of val1[0],val1[1]... and so on. It will be easier to store all the data in a single array location i.e.
arr[1] = "45:47:89:fd:12",
arr[2] = "47:AC:1b:24:58" and so on.
Is this right?
Serial.printf("Val is : %s", val1[0]);
%s expects a string of characters, i.e. a char * or const char * variable. val1 is a const char *, so val1[0] is a char that is the first character within val1. You need to change %s to %c, or else Serial.printf will believe the value of val1[0] is an address to a string of characters, causing a crash or undefined behavior.
If you meant for val1 to be an array of strings, you need to declare it as that. For example:
const char *val1[50];
val1[0] = advertisedDevice.getAddress().toString().c_str();
Serial.printf("Val is : %s", val1[0]); // Now this will work
Edit: If you're looking to build a list of strings out of arr, you should be able to simply assign to arr and access the strings through it:
String arr[50];
loop{
arr[i] = advertisedDevice.getAddress().toString().c_str();
// If above doesn't work, try: arr[i] = String(...);
Serial.printf("Advertised Device: %s \n", arr[i]);
i++;
}
I'm trying to extract two numbers separated by a space from a string and save them as two ints. For example:
if input_string = "1 95" then:
servo_choice = 1
input_number = 95
Code:
String input_string = "";
int input_number = 0;
int servo_choice = 0;
input_string = Serial.readString();
sscanf( input_string, "%d %d", &servo_choice, &input_number );
The IDE gives me this error:
exit status 1
cannot convert 'String' to 'const char*' for argument '1' to 'int scanf(const char*, ...)'
Edit: I guess
input_number = input_string.substring(1,5).toInt();
Actually works and does what I want. I'd still like to know how to get sscanf to work if possible.
Thanks for any replies in advance..
You could try to convert your String into a char array with toCharArray and pass that to sscanf. Something like that (not tested though)
int buffer_len = input_string.length() + 1;
char buffer[buffer_len];
input_string.toCharArray(buffer, buffer_len);
sscanf(buffer, "%d %d", &servo_choice, &input_number);
The String is a class, not a basic type. That means that you need a method to convert / return a pointer to char if you want to use it in a sscanf. That method exists and it's called c_str() .
So, your line has to be:
sscanf( input_string.c_str(), "%d %d", &servo_choice, &input_number );
I'm saving characters from a c file in this array
char *idTable[100];
Inside a while loop,
if(ntoken == 1){
idTable[numId] = yytext;
printf(" \nVariable %s", idTable[numId]);
printf(" Found\n");
numId++;
}
and then iterate through the array. The variable yytext is supposed to have only identifiers and variables like int i, int j, int cont
When I print those character inside the loop, it shows me the variables that I want to save. But when I iterate the array it takes all the text from the variable to the bottom:
while(i<numId){
printf("%d", i );
printf("%s", idTable[i]);
i++;
}
So,
printf(" \nVariable %s", idTable[numId]);
printf(" Found\n");
Will print characters like Variable i Found But printf("%s", idTable[i]); Will always print text inside from the file I want to see. Something like this:
i;
int j;
char c;
char cadena;
float z;
int 89aa12;
z=14.9e-8;
z= 3454y45hrthtrh;
z== 3454y45hrthtrh;
z= 3454y45hrthtrh;
z=12.9;
cadena="Hola";
scanf ("%d",i);
i=i*2;
printf ("El doble es %d",i);
Y="Cualquier Cosa 1";
u=z+y
You're saving a pointer to the same memory in each element of idTable, so whatever that memory is set to last is what each one will be pointing to.
You need to allocate additional memory for each string you want to save (or use a std::string).
strdup may do what you want.
idTable[numId] = strdup(yytext);
but don't forget to free that memory when you're done with it.
Why does my comportstr get changed in this code to a garbage value? I don't understand how my char array could change values if nothing about it is altered. There is nothing else between those two print statements.
int main(int argc, char* argv[])
{
char comportstr[10];
sprintf(comportstr,"COM%d",COMPORT_NUM);
if(DEBUGGING) fprintf(stderr,"str is: %s\n", comportstr); //prints str is: COM3
sprintf(curtime , "%s" , currentDateTime());
if(DEBUGGING) fprintf(stderr,"str is: %s\n", comportstr); //prints str is: ;32
}
Here's what currentDateTime does. It doesn't modify comportstr at all.
// Gets current date/time, format is YYYY-MM-DD.HH;mm;ss
const std::string currentDateTime()
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://www.cplusplus.com/reference/clibrary/ctime/strftime/
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%H;%M;%S", &tstruct);
return buf;
}
In your currentDateTime() function you are returning a std::string which is passed to sprintf()'s vararg interface. That doesn't work as you can't pass standard layout types to vararg interfaces. That is, the second call to sprintf() results in undefined behavior.
You can avoid the problem by using
sprintf(curtime , "%s" , currentDateTime().c_str());
... or, actually,
strcpy(curtime, currentDateTime().c_str());
sprintf(curtime , "%s" , currentDateTime());
The currentDateTime function returns a std::string, but %s is for C-style strings only. You want currentDateTime().c_str(). Your compiler should have given you a warning.
I have a dummy question. I would like to print an integer into a buffer padding with 0 but I cannot sort it out the sprintfformat.
I am trying the following
char buf[31];
int my_val = 324;
sprintf( buf, "%d030", my_val );
hoping to have the following string
"000000000000000000000000000324"
what am I doing wrong? It doesn't mean pad with 0 for a max width of 30 chars?
"%030d" is the droid you are looking for
You got the syntax slightly wrong; The following code produces the desired output:
char buf[31];
int my_val = 324;
sprintf( buf, "%030d", (int)my_val );
From Wikipedia's Article on Printf:
[...] printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".
The padding and width come before the type specifier:
sprintf( buf, "%030d", my_val );
Try:
sprintf( buf, "%030d", my_val );
Your precision and width parameters need to go between the '%' and the conversion specifier 'd', not after. In fact all flags do. So if you want a preceeding '+' for positive numbers, use '%+d'.
It's %030d, with type-letter at the end.
A fairly effective version that doesn't need any slow library calls:
#include <stdio.h>
void uint_tostr (unsigned int n, size_t buf_size, char dst[buf_size])
{
const size_t str_size = buf_size-1;
for(size_t i=0; i<str_size; i++)
{
size_t index = str_size - i - 1;
dst[index] = n%10 + '0';
n/=10;
}
dst[str_size] = '\0';
}
int main (void)
{
unsigned int n = 1234;
char str[6+1];
uint_tostr(n, 6+1, str);
puts(str);
}
This can be optimized further, though it is still probably some hundred times faster than sprintf as is.