Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
TASK: // target - starting an argument in which to record results
target should be a "source" left supplemented with "fill_char" to length "cnt". If cnt is less than the length of the source, it becomes equal to the target source.
// Now is moving on right and must to change something but I'm not sure what and how. Can you give me advice. And if you have some different decision please share with me. Thank you :)))!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <batch_util.h>
int lpad(char* target, char* source, char fill_char, int cnt)
{
int i;
int source_size = strlen(source);
for (i = 0; i < source_size; i++)
target[i] = source[i];
for (i = source_size; i < cnt; i++)
target[i] = fill_char;
target[i] = '\0';
return 0;
}
int main(int argc, char* argv[])
{
char source[128];
char target[128];
char fill_char;
int cnt;
scanf("%s\n", &source);
scanf("%c\n", &fill_char);
scanf("%d\n", &cnt);
lpad(target, source, fill_char, cnt);
printf("%s\n", target);
return 0;
}
For starters you can use standard C string functions instead of loops.
It seems you mean the following
#include <stdio.h>
#include <string.h>
char * lpad( char *target, const char *source, char fill_char, size_t cnt )
{
size_t source_size = strlen( source );
if ( source_size < cnt )
{
memset( target, fill_char, cnt - source_size );
}
strcpy( target + ( source_size < cnt ? cnt - source_size : 0 ), source );
return target;
}
#define N 16
int main(void)
{
char *source= "monkey";
char target[N];
puts( lpad( target, source, '*', N - 1 ) );
return 0;
}
The program output is
*********monkey
As for your code then the function does not append anything to the left.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Using ansi c
#define STDC_VERSION 201112L
I'm new to c, but took my lead from Here
Regardless of the approaches I've tried, I can't get the sum pointer to return.
Running the code succeeds (creates the correct number), and the printf in the addNumericStrings function works, but the printf in the main does not (prints nothing). I assume due to an error prior. I'm not getting any warnings on the build.
output
addNumericStrings.sum = 11234567889
main
#include <stdio.h>
#include <stdlib.h>
#include "addViaStrings.h"
int main(void) {
char s1[] = "9999999999";
char s2[] = "1234567890";
char *sum = addNumericStrings(s1, s2);
printf("main.sum = %s\n", sum);
}
functions
#include <stdio.h>
#include <stdlib.h>
char addNumericStrings(char *s1, char *s2);
char leftPad(char *result, char *s, int maxlength);
int findMaxLength(char *s1, char *s2);
char addNumericStrings(char *s1, char *s2){
int maxlength = findMaxLength(s1, s2);
char addend1[maxlength];
char addend2[maxlength];
char *sum = (char *) malloc(sizeof(char) * (maxlength + 2) );
int a1, a2, total;
int carry = 0;
// char sum[(maxlength + 2)]; // +1 in case addition rolls over past maxlength
// Prepare the strings for manual addition
leftPad(addend1, s1, maxlength);
leftPad(addend2, s2, maxlength);
// Buffer sum with ascii zeros (#48), not 0, and not "\0"
for (int i = 0; i < (maxlength + 1); i++) { sum[i] = 48; }
sum[maxlength + 1] = 0;
// Run the manual addition
// Start adding individual ints from end (right side)
for (int i = maxlength - 1 ; i >= 0; i--) {
a1 = addend1[i] - '0'; // Convert to int
a2 = addend2[i] - '0'; // Convert to int
total = (a1 + a2 + carry);
carry = 0;
if ( total >= 10){
carry += 1;
total -= 10;
}
sum[i +1] = 48+total; // convert to ascii value for numbers (adding 48)
}
sum[0] = 48+carry; // add last carry to start of num always, even if 0
sum[maxlength + 1] = '\0';
printf("addNumericStrings.sum = %s\n", sum);
return sum;
}
char leftPad(char *result, char *s, int maxlength){
// Pads number to [000123456789]
( ...snip... )
}
int findMaxLength(char *s1, char *s2){
// Returns int value of the length of the longer between s1 and s2
int length1 = strlen(s1);
int length2 = strlen(s2);
int maxlength;
(length1 > length2) ? (maxlength = length1) : (maxlength = length2);
return maxlength;
}
If you want to return a char * from your function, you have to use the appropriate return type:
char* foo(void)
// ^
{
char *bar;
// ...
return bar;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I got string containing numbers separated by spaces. Numbers can be single-digit, two-digit, or perhaps more-digit. Check the example.
"* SEARCH 2 4 5 12 34 123 207"
I don't know how long the string is (how many numbers it contains), so I cant initiate the array properly. The result should look like this:
array = {2,4,5,12,34,123,207}
Do you have any ideas how to perform this?
like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *input = "* SEARCH 2 4 5 12 34 123 207";
int len = 0;
sscanf(input, "%*[^0-9]%n", &len);//count not-digits(The Number isn't negative)
char *p = input + len;
char *start = p;
int v, n = 0;
while(1 == sscanf(p, "%d%n", &v, &len)){
++n;//count elements
p += len;
}
int array[n];//or allocate by malloc(and free)
char *endp = NULL;
int i;
for(i = 0; i < n; ++i){
array[i] = strtol(start, &endp, 10);
start = endp + 1;
}
//check print
for(i = 0; i < n; ++i)
printf("%d ", array[i]);
puts("");
return 0;
}
You can try this approach. It uses a temporary buffer to hold the current integer that is being processed. It also uses dynamic arrays, to deal with different lengths of the string you want to process, and expands them when necessary. Although using strtok Would be better in this situation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char *argv[]) {
char message[] = "* SEARCH 2 4 5 12 34 123 207";
char *buffer = NULL;
int *integers = NULL;
int buff_size = 1, buff_len = 0;
int int_size = 1, int_len = 0;
int ch, messlen, i, first_int = 0;
/* creating space for dynamic arrays */
buffer = malloc((buff_size+1) * sizeof(*buffer));
integers = malloc(int_size * sizeof(*integers));
/* Checking if mallocs were successful */
if (buffer == NULL || integers == NULL) {
fprintf(stderr, "Malloc problem, please check\n");
exit(EXIT_FAILURE);
}
messlen = strlen(message);
/* going over each character in string */
for (ch = 0; ch < messlen; ch++) {
/* checking for first digit that is read */
if (isdigit(message[ch])) {
first_int = 1;
/* found, but is there space available? */
if (buff_size == buff_len) {
buff_size++;
buffer = realloc(buffer, (2*buff_size) * sizeof(*buffer));
}
buffer[buff_len++] = message[ch];
buffer[buff_len] = '\0';
}
/* checking for first space after first integer read */
if (isspace(message[ch]) && first_int == 1) {
if (int_size == int_len) {
int_size++;
integers = realloc(integers, (2*int_size) * sizeof(*integers));
}
integers[int_len] = atoi(buffer);
int_len++;
/* reset for next integer */
buff_size = 1;
buff_len = 0;
first_int = 0;
}
/* for last integer found */
if (isdigit(message[ch]) && ch == messlen-1) {
integers[int_len] = atoi(buffer);
int_len++;
}
}
printf("Your string: %s\n", message);
printf("\nYour integer array:\n");
for (i = 0; i < int_len; i++) {
printf("%d ", integers[i]);
}
/* Being careful and always free at the end */
/* Always a good idea */
free(integers);
free(buffer);
return 0;
}
You can read each character and verify if it is in range of >=48(Ascii of 0) and less than = 57(Ascii of 9). If so is the case read them into a array Otherwise you could copy them to a temporary string and convert to int using functions like atoi()
#include <stdio.h>
int main(int argc, char *argv[])
{
int j=0,k,res;
char buff[10];
while(str[j])
{
if((str[j]>='0')&&(str[j]<='9'))
{
k=0;
while((str[j]!=' ')&&(str[j]!='\0'))
{
buff[k]=str[j++];
k++;
}
buff[k]=0;
res=atoi(buff);
//Store this result to an array
}
j++;
}
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to generate a random string of only lower-case ASCII characters (meaning lower case letters, numbers, and other ASCII characters; just no upper-case lettesr).
The max length of the string should be 587 characters (including null terminator).
How would I go about doing this?
Thanks
#define N 588
#include <stdlib.h>
#include <time.h>
void gen(char *dst)
{
int i, n;
srand(time(NULL)); /* init seed */
if ((dst = malloc(N)) == NULL) /* caller will need to free this */
return;
for (i = 0; i < N; )
if ((n = rand()) < 'A' && n > 'Z')
dst[i++] = n;
dst[N - 1] = 0; /* null terminate the string */
}
I tried this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define BUFFER_SIZE 587 /* 587 including NULL so 0..585 and 586 is NULL */
int main(int argc, char** argv)
{
size_t i;
char buffer[BUFFER_SIZE];
int x;
srand((unsigned int)time(NULL));
memset(buffer, 0, sizeof(buffer));
for (i = 0; i < BUFFER_SIZE-1; i++)
{
/* Note: islower returns only a b c..x y z, isdigit 0..9 and isprint only printable characters */
do
{
x = rand() % 128 + 0; /* ASCII 0 to 127 */
}
while (!islower(x) && !isdigit(x) && !isprint(x));
buffer[i] = (char)x;
}
buffer[BUFFER_SIZE-1] = '\0';
printf("%s", buffer);
getchar();
return EXIT_SUCCESS;
}
This way you can do a random string with whatever characters you want. The only thing is you should put them in the function
#include <stdlib.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a char* formatted like:
* SEARCH 1 2 3 ...
with a variable number of integers separated by spaces. I would like to write a function to return an int[] with the integers after * SEARCH.
How should I go about writing this function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *f(const char *s, int *n /* out */){
if(strncmp(s, "* SEARCH", 8)!=0){
fprintf(stderr, "format error!\n");
*n = 0;
return NULL;
}
s += 8;
const char *p = s;
int v, len, status;
int count = 0;
while((status=sscanf(p, "%d%n", &v, &len))==1){
++count;
p +=len;
}
if(status==0){
fprintf(stderr, "format error!\n");
*n = 0;
return NULL;
}
int *ret = malloc(count * sizeof(*ret));
p = s;
count = 0;
while(EOF!=sscanf(p, "%d%n", &v, &len)){
ret[count++]=v;
p +=len;
}
*n = count;
return ret;
}
int main (void){
int i, n, *nums = f("* SEARCH 1 2 3", &n);
for(i=0; i<n; ++i)
printf("%d ", nums[i]);
printf("\n");
free(nums);
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone give me a complete example of how to generate an Alphanumeric String randomly
like (ARG534UJ6) using C ? I'm completely new to C.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
This is not working.
As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)
My guess is that you don't have room for your string, try:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
int main(void)
{
char *str = malloc(8 + 1);
/* initialize random seed: */
srand(time(NULL));
gen_random(str, 8);
printf("%s\n", str);
free(str);
return 0;
}