return array to coder.ceval - c

I need to call a c-function from matlab using y=coder.ceval() and return a string from the function. However the coder.ceval() function only allows me to return a scalar value. String is however an array of char, and thus cannot be returned. The code in matlab function looks like:
function y = abc(param)
y = '';
if strcmp(coder.target,'rtw'),
y=coder.ceval('c-function',param);
end
end
Is there any solution or workaround for it?
Looking forward for some help. Thank you very much!

EDITING
This is a workaround and you should use it at your own risk! ;)
I mean if it is really your last option.
As you do not specify the kind of string I assume for simplicity that it is composed only by uppercase letters (AABBBCC).
Uppercase letters are represented as decimal numbers by 2 digits (A = 65, Z = 90, man ascii).
This method comprises two steps:
1) In your function that you call via coder.ceval you should build a scalar value from the string you want to return. 2) You have to rebuild the string from the scalar value.
The following code illustrates by a simple example how to carry out the two steps. Keep in mind that is only an example and you have to work on it. Let's suppose for example that you need to return the string "ABC" then you can return the scalar "656667" which is composed by the three 2-digits numbers: 65=A, 66=B, 67=C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i, len, n;
// First convert a string in a scalar value
char str[] = {'A', 'B', 'C', '\0'};
printf("str = %s\n", str);
len = strlen(str);
for (i = 0; i < len; i++) {
n = str[i] + i*100;
}
printf("n = %d\n", n);
// You return a scalar that is composed by 65,66,67 ---> A,B,C
int y = 656667;
char num[100];
char letter[3];
// convert the number in a string
snprintf(num, 100, "%d", y);
printf("num = %s\n", num);
len = strlen(num);
printf("num len = %d\n", len);
// here we assume that the number of digits id even only ascii letters
if ((len%2) != 0) exit(1);
// Now we have to store the number of two digits as numbers and
// then convert the to char and finally append tehm to a string
int *ni = malloc((len/2)*sizeof(int));
char *string = malloc(len + 1);
// Here I use a lot of intermediate steps to make it clear
char c = 0;
for (i = 0; i < len/2; i+=1) {
snprintf(letter, 3, "%c%c", num[2*i], num[2*i+1]);
ni[i] = atoi(letter);
c = (char)ni[i];
printf("letter %d = %s, x = %d, c = %c\n", i, letter, ni[i], c);
string[i] = c;
printf("string[%d] = %c\n", i, string[i]);
}
// print the final string
string[len] = '\0';
printf("string = %s\n", string);
return 0;
}
Lowercase letters starts at 97 but then become 3 digits, however by using some "special number" of 2 digits one can even decide to read 2 digits at the beginning of the string and 3 digits after the "special number".
Ok, I am not sure that this will help but, at least, I hope you find it interesting.

Related

How to convert a string to a complete integer number in C?

I have tried in this way:
//Write a program to find out the reverse order of a given integer
#include <stdio.h>
int
main(void){
//Put variables for the further proceed
int number, quotient=1, remainder;
//Declare a character array
char text[]="princeX";
//Show the message to the user
printf("Enter an integer number :");
//Taking input from the user
scanf("%d",&number);
//To find out the integer number in the reverse order
while(quotient!=0){
quotient=number/10;
remainder=number%10;
number=quotient;
text[6] = remainder + '0';
puts(text);
}
//Converts the string to a whole integer
int numberUpdate=atoi(text);
printf("%d",numberUpdate);
}
I want to achieve: The user will give an integer number then my system will give the reverse order of the given integer number. To accomplish this goal I stored an integer into a character array but not entirely.
For the input: 123456
Output shows like from my code:
prince6
prince5
prince4
prince3
prince2
prince1
Bu my expectation was:
6
5
4
3
2
1
After that, I just simply wanted to print those as an integer. But I could not do that. When I am going to transform these characters into an integer but the output shows zero. Which problem I have been made in my program and how can I solve that puzzle?
The problem started with this line text[6] = remainder + '0';
puts(text); You only changed text[6], which contains ‘X’ and then printed then whole text. That explains why you go
Prince6
Prince5
Prince4
Prince3
Prince2
Prince1
If you want to get the correct output, you should make these changes:
Declare another variable i=0 before while loop.
Replace the problematic lines with text[i] = remainder+‘0’; printf(“%c\n”, text[i]); i++;
You do this because you want to replace all elements within the text. Then you should expect the correct output. These line int numberUpdate=atoi(text);
printf("%d",numberUpdate); will work afterward. It didn’t work at first simply because it couldn’t convert a string with letters into numbers. Since your string only contains number now, everything should work fine as expected.
I hope it was helpful for you, I did my best explaining the issue, I hope you can understand by reading it. :)))
Here you have number to string conversion function.
char *reverse(char *str)
{
char *wrk = str, *end;
if(str)
{
end = str + strlen(str) -1;
while(end > str)
{
char tmp = *wrk;
*wrk++ = *end;
*end-- = tmp;
}
}
return str;
}
char digits[] = "01234567890abcdefghijklmnopqrstxyvwz";
char *convert(char *buff, unsigned long long val, int radix)
{
char *tmp = buff;
if(radix > sizeof(digits) - 1 || radix < 2) return NULL;
while(val)
{
*tmp++ = digits[val % radix];
val /= radix;
}
*tmp = 0;
return reverse(buff);
}
int main(void)
{
char str[30];
printf("decimal: %s\n", convert(str, 345676, 10));
printf("binary: %s\n", convert(str, 345676, 2));
printf("octal: %s\n", convert(str, 345676, 8));
printf("hex: %s\n", convert(str, 345676, 16));
printf("Base 5: %s\n", convert(str, 345676, 5));
printf("Base 29: %s\n", convert(str, 345676, 29));
}
https://godbolt.org/z/6Ge6bs

How can I extract an integer from within a string?

I'm working on an assignment and as part of it I need to extract the integer from a string.
I've tried using the atoi() function, but it always returns a 0, so then I switched up to strtol(), but it still returns a 0.
The goal is to extract the integers from the string and pass them as arguments to a different function. I'm using a function that then uses these values to update some data (update_stats).
Please keep in mind that I'm fairly new to programming in the C language, but this was my attempt:
void get_number (char str[]) {
char *end;
int num;
num = strtol(str, &end, 10);
update_stats(num);
num = strtol(end, &end, 10);
update_stats(num);
}
The purpose of this is in a string "e5 d8" (for example) I would extract the 5 and the 8 from that string.
The format of the string is always the same.
How can I do this?
strtol doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)
If you need to find where a number starts, you can use something like:
const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/
(man strpbrk)
If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -. But watch out for the beginning of the string:
if ( nump != str && nump[-1] == '-') --nump;
Just putting - into the strpbrk argument would produce false matches on input like non-numeric7.
If the format is always like this, then this could also work
#include <stdio.h>
int main()
{
char *str[] = {"a5 d8", "fe55 eec2", "a5 abc111"};
int num1, num2;
for (int i = 0; i < 3; i++) {
sscanf(str[i], "%*[^0-9]%d%*[^0-9]%d", &num1, &num2);
printf("num1: %d, num2: %d\n", num1, num2);
}
return 0;
}
Output
num1: 5, num2: 8
num1: 55, num2: 2
num1: 5, num2: 111
%[^0-9] will match any non digit character. By adding the * like this %*[^0-9] indicates that the data is to be read from the string, but ignored.
I suggest you write the logic on your own. I know, it's like reinventing the wheel, but in that case, you will have an insight into how the library functions actually work.
Here is a function I propose:
bool getNumber(str,num_ptr)
char* str;
long* num_ptr;
{
bool flag = false;
int i = 0;
*num_ptr = 0;
char ch = ' ';
while (ch != '\0') {
ch = *(str + i);
if (ch >= '0' && ch <= '9') {
*num_ptr = (*num_ptr) * 10 + (long)(ch - 48);
flag = true;
}
i++;
}
return flag;
}
Don't forget to pass a string with a \0 at the end :)

How to fix my code of reducing string sizes to their "effective size"

I want to make a code that reads a string, and then tranposes this string into a new one with length equal to the effective length of the original string, that is,
old string = stringi
new string = stringii
newstring[strlen(stringi)+1] (where +1 is for the terminator '\0'
I do this for two strings (string 1 and string 2), and in the end I print ‍strlen(string1), strlen(string2), and print also string11 and string22 (to see whether it worked).
Well, what's the problem? The program compiles right.
But if I type "sugar" for string 1 and "sugara" for string 2, it returns:
sugar
sugara'
Or if I type batata and cenoura it returns:
batata'
cenoura
Or if I type cenoura and batata it returns:
cenoura
batata'
I don't know what's the motive of this problem. If anyone could help me searching for bugs in the code (or suggesting another alternative for doing the problem)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//Here I create two strings with size 100
char string1[100], string2[100];
//Here I ask for the user to type two phrases and store them using gets
printf("Type two phrases):\n");
gets(string1);
gets(string2);
//Here I create two new strings with size given by strlen(stringi)+1
char string11[strlen(string1)+1];
char string22[strlen(string2)+1];
//For string 1, I atrribute all the values of the original string to the new string, until '\0'
for (int i = 0; string1[i] != '\0'; i++)
{
string11[i] = string1[i];
}
//Here I denote the last position of the new string with the terminator
string11[strlen(string1)+1] = '\0';
//I do the same for string 2
for (int i = 0; string2[i] != '\0'; i++)
{
string22[i] = string2[i];
}
string22 [strlen(string2)+1] = '\0';
//I print the length of the original strings and the new strings
printf("length string 1 = %d length string 2 = %d\n", strlen(string1), strlen(string2));
printf("%s\n%s\n", string11, string22);
system("pause");
return 0;
}
These statements
string11[strlen(string1)+1] = '\0';
tring22 [strlen(string2)+1] = '\0';
are wrong.
You have to write
string11[strlen(string1)] = '\0';
tring22 [strlen(string2)] = '\0';
This call is also wrong
printf("length string 1 = %d length string 2 = %d\n", strlen(string1), strlen(string2));
You have to write
printf("length string 1 = %zu length string 2 = %zu\n", strlen(string1), strlen(string2));
Pay attention to that the function gets is not a standard C function any more. Use instead fgets.
For example
fgets( string1, sizeof( string1 ), stdin );
string1[ strcspn( string1, "\n" ) ] = '\0';
Hello you didn't need to increment with 1 at initilisation of tables length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
//Here I create two strings with size 100
char string1[100], string2[100];
//Here I ask for the user to type two phrases and store them using gets
printf("Type two phrases):\n");
gets(string1);
gets(string2);
//Here I create two new strings with size given by strlen(stringi)+1
char string11[strlen(string1)];
char string22[strlen(string2)];
//For string 1, I atrribute all the values of the original string to the new string, until '\0'
for (int i = 0; string1[i] != '\0'; i++)
{
string11[i] = string1[i];
}
//Here I denote the last position of the new string with the terminator
string11[strlen(string1)] = '\0';
//I do the same for string 2
for (int i = 0; string2[i] != '\0'; i++)
{
string22[i] = string2[i];
}
string22 [strlen(string2)] = '\0';
//I print the length of the original strings and the new strings
printf("length string 1 = %d length string 2 = %d\n", strlen(string1), strlen(string2));
printf("%s\n%s\n", string11, string22);
system("pause");
return 0;
}
good luck.

How to do read multiple characters from an argument

I am trying to read multiple characters from an argument in c. So when the person rules the file like "./amazing_program qwertyyuiopasdfghjklzxcvbnm" it would read the qwerty characters and store the, into a array as a number (ASCII) like:
array[0] = 'q';
array[1] = 'w';
array[2] = 'e';
array[3] = 'r';
array[4] = 't';
array[5] = 'y';
and so on...
My goal: Is to separate the argument into each individual character and store each individual character into a different place in the array (like shown above).
I tried this way, but it didn't work.
int user_sub = 0;
int argument = 1;
while (argument < argc) {
user_sub = atoi(argv[argument]);
argument = argument + 1;
}
From reading your comments, I've come to understand you just want to be able to get to the characters so you can do a shift. Well, that's not so hard to do, so I've tried to show you how you can do it here without having to complete the Caesar logic for you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SHIFT 13
int main (int argc, const char *argv[]) {
// Verify they gave exactly one input string.
if (argc != 2) {
fprintf(stderr, "Usage: %s <word>\n", argv[0]);
exit(EXIT_FAILURE);
}
// A string IS already an array of characters. So shift then and output.
int n = strlen(argv[1]);
for (int i = 0; i < n; i++) {
char c = argv[1][i];
// Shift logic here: putchar(...);
printf("%d: %c\n", i, c);
}
return EXIT_SUCCESS;
}
The key takeaway is that a string is already an array. You don't need to make a new array and stick all the characters in it. You already have one. What this program does is simply "extract" and print them for you so you can see this. It currently only writes the current argument string to output, and does no shifting. That's for you to do. It also doesn't take into account non-alphabetical characters. You'll have to think about them yourself.
You have serious lack :
1)
A string in C is an ARRAY of type char. We know where the end of the array is thank to a special value : '\0'.
Now, you have to deeply understand that each case of the array contain a NUMBER : since the type of the case is char, it will be a number in the range [-128, 127] (yeah, I know that char is special and can be signed or not, but let's keep it simple for the time being).
So if you acces each case of the array and print it, you will have a number between -128 and 127. So how the program know to print a letter instead of a number ? And how do he know which letter for which number ?
Thank to an internal table used for this uniq purpose. The most common is the ASCII table. So if a case of the array is 65, what will be printed is 'A'.
2) How can I go through each case of a string ? (which is an array of char terminated by '\0') ?
Simply with a for loop.
char str[] = "test example";
for (size_t i = 0; str[i] != '\0'; ++i) {
printf("The %d letter is '%c'\n", i, str[i]);
}
Again, since it's a number in str[i], how the program know how to print a letter ? Thank to the "%c" in printf, meaning "print the letter using the table (probably ASCII)". If you use "%s", it's the same thing, but you have to give the array itself instead of a case of the array.
So, what if I want to print the number instead of the letter ? Just use "%d" in printf.
char str[] = "test example";
for (size_t i = 0; str[i] != '\0'; ++i) {
printf("The %d letter is '%c' and it's real value is %d\n", i, str[i], str[i]);
}
Now, what if we increment all the value in each case of the string ?
char str[] = "test example";
for (size_t i = 0; str[i] != '\0'; ++i) {
str[i] = str[i] + 1; // Or ++str[i];
}
for (size_t i = 0; str[i] != '\0'; ++i) {
printf("The %d letter is '%c' and it's real value is %d\n", i, str[i], str[i]);
}
We have changed the string "test example" into "uftu fybnqmf".
Now, for your problem, you have to take the resolution step by step :
First, make a function that alter (cypher) a string given in argument by adding a shift.
void CesarCypherString(char *string);
Beware of "overflow" ! If I want to have a shift of 5, then 'a' will become 'f', but what happen for 'z' ? It should be 'e'.
But if you look at the ascii table, 'a' = 97, 'f' = 102 (and it make sense, since 'a' + 5 = 'f', 97 + 5 = 102), but 'z' is 122 and 'e' is 101. So you cannot directly do 'z' + 5 = 'e' since it's wrong.
Hint : use modulo operator (%).
Next, when you have finished to do the function CesarCypherString, do the function CesarDecypherString that will decypher a string.
When you have finished, then you can concentrate on how to read/duplicate a string from argv.

C programming. Function to generate a string of random letters using only arrays and then pointers

Im trying to code a program in C to generate a string containing random letters using only arrays first and then again using pointers. I've looked at many other questions but is not quite what I'm trying to accomplish. I can really use help please.
Function 1- Generates a string with random upper
case letter A-Z with 40 characters.
Function 2- Function to let user enter a string
with random upper case letter and a replacement character.
Function 3- Searches string1 from function 1 and replaces
occurences of any character from string 2 (user entered) with
replacement character.
OUTPUT EX.
String 1- "AABBCCDDEEFFGGHHABCDEFGH"
String 2- "BE"
Replacement char- "3"
Filtered string- AA33CCDD33FFGGHHA3CD3FGH.
This is what I have so far, Im not very good with arrays.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int s1 [41];
srand(time(NULL));
int i;
for (i = 0; i < 41; i++)
{
s1 [i] = rand();
}
return 0;
}
Any help will be appreciated.
Thanks alot.
#include <stdio.h>
#include <stdlib.h>
void rand_str(char* txt, size_t sz)
{
int i=sz-1;
while( i --> 0 )
{
txt[i] = 'A' + rand() % 26;
}
printf("Random Str: %.*s\n", sz+i, txt);
}
void fn2(char* tgt, size_t sz, char* repl )
{
puts("String 2: ");
fgets(tgt, sz, stdin);
puts("Replacement Char: ");
*repl = getchar();
}
void search_replace(char* txt, char* tgt, char repl)
{
while(*tgt != '\0')
{
while ((strchr(txt, *tgt) ? (tgt[strchr(txt, *tgt)-tgt] = repl) : 0) == repl);
tgt++;
}
}
int main(void)
{
char txt[41] = {0};
char tgt[40] = {0};
char repl;
rand_str(txt, sizeof(txt));
fn2(tgt, sizeof(tgt), &repl);
search_replace(txt, tgt, repl);
return !printf("Filtered String: %s\n", txt);
}
Please note that I did not compile any of this code. It might have some typo and/or runtime errors. The concept is correct though and you should understand the code first and not just copy it.
Function 1:
#include <stdlib.h> // Important! rand() function that generate random function is in that library!
//This function returns a pointer of an array (arr). In other words it returns the **address** of the first character of the array.
// Assuming arr is valid!
char* randomString(char* arr){
// This part does not REALLLYY matters it just makes sure the random will truly be random...
time_t t;
srand((unsigned) time(&t)); // Seeds the random function.
//------------------
//Looping the array assigning random letters:
int i = 0;
while(i<SIZE){
arr[i] = 'A'+(rand()%('Z'-'A'+1));// 'A' has a numerical value, we want the range from 'A' to 'Z' to be random. 'Z'-'A' is the range of letters (26) because its a modulu if the modulu was just 'Z'-'A' (26) it wouldnt print Z. 'Z' is the 26th letter, 26%26 is zero, it will not give 'Z' this is why I increased 'Z'-'A' by 1 so the modulu will include 'Z' as random latter.
i = i + 1;
}
arr[i] = 0;// String terminator also called NULL.
return "lol";
}
Function 2:
#include <string.h>
int replace(char* inputString, char* userInput,char replacement ){
/* e.g.
inputString = "ABSDSADASBBBAA";//Generate yourself... (Might want to user function 1)
userInput = "AB"; // You need to do the user input yourself...
replacement = 'D';
*/
int i = 0;
while(i<strlen(inputString)){
int j = 0;
while(j<strlen(userInput)){
if(inputString[i]==userInput[j]){
inputString[i] = replacement;
}
j = j+1;
}
i = i + 1;
}
}
Function 3:
int main(){
// Just use regular IO libraries to get user's input...
// Assuming you did that, I will hard code the values (you need to do the IO e.g. gets())
char str[SIZE];
randomString(str); // Requirement #1 reuse of function 1
char * userInput = "AB"; // You need to do the user input yourself...
char replacement = 'D';// You need to do the user input yourself...
replace(str, userInput, replacement)//Requirement #2
return 0;
}

Resources