Is there a C function that can concatenate all the passed arguments (except the name of the executable) into a char* and return it?
Try that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned int i;
size_t len = 0;
char *_all_args, *all_args;
for(i=1; i<argc; i++) {
len += strlen(argv[i]);
}
_all_args = all_args = (char *)malloc(len+argc-1);
for(i=1; i<argc; i++) {
memcpy(_all_args, argv[i], strlen(argv[i]));
_all_args += strlen(argv[i])+1;
*(_all_args-1) = ' ';
}
*(_all_args-1) = 0;
printf("All %d args: '%s'\n", argc, all_args);
free(all_args);
return 0;
}
Why would there be ? Just use strcat in a loop.
Something like this? No guarantees that this will compile.
#include <string.h>
#include <stdio.h>
int main(int argc, char ** argv) {
int i;
int len = 1;
char * str;
for (i = 1; i < argc; i++) {
len += strlen(argv[i]);
}
str = malloc(sizeof(char)*len);
str[0] = '\0';
for (i = 1; i < argc; i++) {
strcat(str, argv[i]);
}
//Use str for whatever you want
printf("My string is %s\n", str);
free(str);
}
I don't think there's such a function, but if I'm not wrong, you just have to :
get the length : len = strlen(argv[1]) + strlen(argv[2]) + ... and check for overflow
use malloc : malloc(len + 1) * sizeof(char))
set your_copy[0] to '\0'
use strcat(your_copy, argv[1]), strcat(your_copy, argv[2])... for each remaining argv[]
EDIT : Oh, the previous answer may be better. ;)
Related
I'm trying to write my own concatenate program. What I'm doing is getting two strings as input from argv, creating a third empty character array that holds the length of argv[1] + argv[2], and then use two for loops to insert the characters from each argv string into the third string.
My first for loop seems to be working fine buy my second for loop isn't doing anything. Any ideas?
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strnlen(string1, 50);
int string2Len = strnlen(string2, 50);
char string3[string1Len + string2Len + 1];
for (int i = 0; i <= string1Len; i++)
{
string3[i] = string1[i];
}
for(int i = (string1Len + 1); i <= (string1Len + string2Len); i++)
{
string3[i] = string2[i];
}
string3[string1Len + string2Len + 1] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
You can simplify (and optimize) it by using the memcpy function
int main(int argc, char **argv) {
if (argc < 3) return 1;
const char *string1 = argv[0];
const char *string2 = argv[1];
const size_t string1Len = strlen(string1);
const size_t string2Len = strlen(string2);
char *string3 = malloc((string1Len + string2Len + 1) * sizeof(*string3));
memcpy(string3, string1, string1Len * sizeof(*string1));
memcpy(string3 + string1Len, string2, (string2Len + 1) * sizeof(*string2));
printf("%s %zu %zu", string3, string1Len, string2Len);
free(string3);
return 0;
}
And as the others said, pay attention to the nul terminator
Your second for loop "did nothing" because the first one worked up to the \0 character and included it in string3, so it's better to set the condition that the for loop works up to that character
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strlen(string1);
int string2Len = strlen(string2);
int i;
char string3[string1Len + string2Len +1];
for (i = 0; string1[i]!='\0'; i++)
{
string3[i] = string1[i];
}
string3[i]=' '; //with space
++i;
for(int j = 0; string2[j]!='\0'; j++)
{
string3[i] = string2[j];
i++;
}
string3[string1Len + string2Len + 1] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
There are two main issues in your code. Your first for loop copies the nul terminator from string1; so, anything you then add to your string3 after that will simply be ignored by functions like printf, because they see that nul as marking the end of the string.
In your second for loop, you have the same problem and, more critically, the i index you use is not valid for string2, as you have added the length of string1 to it.
Also, note that arrays in C start at zero, so you shouldn't add the 1 to the position of the final nul terminator.
Here's the "quick fix" for your current code:
for (int i = 0; i < string1Len; i++) { // Use "<" in place of "<=" or we copy the null terminator
string3[i] = string1[i];
}
for (int i = 0; i < string2Len; i++) { // Start "i" at 0 for valid "string2" index ...
string3[i + string1Len] = string2[i]; // ... and add "string1Len" for the destination index
}
string3[string1Len + string2Len] = '\0'; // Arrays start at ZERO, so don't add 1 for "nul" terminator position
However, there are some other points and possible improvements. Note that the strnlen function returns a size_t type, so you would be better off using that for your indexes. Also, as you know that the i index at the end of the first loop will still be valid for the next character, you can re-use that in the second loop (so long as you have declared it outside the first loop), and you can use a second index for the source string.
Also, as pointed out by chqrlie, you really should check that you have sufficient source data in the argv array.
Here's a version of your program with those additional changes:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (argc < 3) {
// Error-handling code
return 1;
}
char* string1 = argv[1];
char* string2 = argv[2];
size_t string1Len = strnlen(string1, 50);
size_t string2Len = strnlen(string2, 50);
size_t i, j;
char string3[string1Len + string2Len + 1];
for (i = 0; i < string1Len; i++) {
string3[i] = string1[i];
}
for (j = 0; j < string2Len; j++, i++) {
string3[i] = string2[j];
}
string3[i] = '\0';
printf("%s %zu %zu\n", string3, string1Len, string2Len); // "%zu" for "size_t"
return 0;
}
The problem in your second loop is that i starts beyond the beginning of the second string. However, if all you are trying to do is to write you own custom (max 50 chars) concatenate program, all you need to do is to printf the arguments one after the other and printf can help limit:
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) printf("%.50s", argv[i]);
printf("\n");
return 0;
}
There is no need to copy in memory to a VLA and print.
If you need to create a function that concatenates, you better use malloc - as you can't safely return a VLA: (note, the following example will not limit to 50 chars):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concat(int argc, char* argv[]) {
size_t totalsize = 1;
for (int i = 0; i < argc; ++i) totalsize += strlen(argv[i]);
char* ret = malloc(totalsize);
if (!ret) exit(1);
if (!argc) *ret = 0;
char* dst = ret;
for (int i = 0; i < argc; ++i) {
char* src = argv[i];
while (*dst++ = *src++); /* Copy also the \0 */
--dst;
}
return ret;
}
int main(int argc, char *argv[])
{
char* str = concat(argc - 1, argv + 1); /* Skip the program name */
printf("%s\n", str);
free(str);
return 0;
}
Note that the above examples will concatenate any number of strings.
The index values in both loops are incorrect:
you should stop the first loop when i == string1Len, hence the test should be:
for (int i = 0; i < string1Len; i++)
you should use add string1Len to the index into the destination string so bytes from the second string are appended to those of the first string:
for (int i = 0; i < string2Len; i++) {
string3[string1Len + i] = string2[i];
}
the index for the null terminator is string1Len + string2Len, adding 1 is incorrect as indexing is zero based in C:
string3[string1Len + string2Len] = '\0';
you should test the actual number of arguments provided to the program to avoid undefined behavior if some are missing.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "missing arguments\n");
return 1;
}
char *string1 = argv[1];
char *string2 = argv[2];
int string1Len = strnlen(string1, 50);
int string2Len = strnlen(string2, 50);
char string3[string1Len + string2Len + 1];
for (int i = 0; i < string1Len; i++) {
string3[i] = string1[i];
}
for (int i = 0; i < string2Len; i++) {
string3[string1Len + i] = string2[i];
}
string3[string1Len + string2Len] = '\0';
printf("%s %d %d\n", string3, string1Len, string2Len);
return 0;
}
I have tried this solution, but don't know why it is giving segmentation fault.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char st[1000]="";
for (int i=1; i<argc; i++)
{
strcat(st,argv[i][0]);
strcat(st,". ");
}
printf("%s", st);
return 0;
}
A solution without using any string-library functions at all might look like:
#include <stdio.h>
#define ARGV_MAX (5) /* Adjust this to match the maximum number of arguments
to be processed. */
#define RESULT_STR_MAX (3*ARGV_MAX +1) /* The chararacters per arg per maximum arguments
to be processed +1 for the 0-terminator. */
int main(int argc, char *argv[])
{
char st[RESULT_STR_MAX] = "";
size_t string_index = 0;
size_t argv_index = 1; /* Skip argv[0] below as it does not carry an
argument, but the program's name. */
while ((size_t) argc > argv_index
&& RESULT_STR_MAX > string_index /* in fact this or
&& ARGV_MAX >= argv_index) this would do. */
{
st[string_index] = argv[argv_index][0];
string_index++;
st[string_index] = '.';
string_index++;
st[string_index] = ' ';
string_index++;
argv_index++;
}
st[string_index] = '\0'; /* Add the '0'-terminator
to make the char array a "string".
(not necessary as st got initialised to all 0s).*/
if (ARGV_MAX < argv_index)
{
printf("Ignored the last %d argument(s).\n", argc - ARGV_MAX - 1);
}
puts(st);
return 0;
}
Below another approach using strcat():
#include <stdio.h>
#define ARGV_MAX (5) /* Adjust this to match the maximum number of arguments
to be processed. */
#define RESULT_STR_MAX (3*ARGV_MAX +1) /* The chararacters per arg per maximum arguments
to be processed +1 for the 0-terminator. */
int main(int argc, char *argv[])
{
char st[RESULT_STR_MAX] = "";
size_t argv_index = 1; /* Skip argv[0] below as it does not carry an
argument, but the program's name. */
while ((size_t) argc > argv_index
&& ARGV_MAX >= argv_index)
{
strcat(st, (char[2]){argv[argv_index][0]});
strcat(st, ". ");
argv_index++;
}
if (ARGV_MAX < argv_index)
{
printf("Ignored the last %d argument(s).\n", argc - ARGV_MAX - 1);
}
puts(st);
return 0;
}
Change this statement
strcat(st,argv[i][0]);
to
strncat(st, &argv[i][0], 1);
or
strncat(st, argv[i], 1);
In the original statement the function considers the character argv[i][0] as a pointer value. So the call has undefined behavior.
Or you can use a straightforward approach without using string functions. For example
#include <stdio.h>
int main( int argc, char * argv[] )
{
char st[1000];
size_t i = 0;
for ( int j = 1; j < argc; j++ )
{
st[i++] = *argv[j];
if ( j + 1 != argc )
{
st[i++] = ',';
st[i++] = ' ';
}
}
st[i] = '\0';
puts( st );
return 0;
}
try this:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char st[1000]="";
--argc, ++argv;//skip first.
char *p = st;
for (int i = 0; i < argc; i++){
if(i){//between ?
strcpy(p, ". ");
p += 2;
}
*p++ = argv[i][0];//copy one character
}
printf("%s\n", st);
return 0;
}
The overall gist of the program is to accept a command-line argument and for each string to print out backwards with variable length.
For example:
$ ./reversecommand hello 102
dnammocesrever/. olleh 201
I am having difficulty in implementing the thought process into code (e.g. with hello below). Any thoughts?
argc[0] ./reversecommand
argc[1] hello
argc[1][0] h -> argc[1][4] o
argc[1][1] e -> argc[1][3] l
argc[1][2] l -> argc[1][2] l
argc[1][3] l -> argc[1][1] e
argc[1][4] o -> argc[1][0] h
argc[2] 102
argc[3] [null]
#include <stdio.h>
#include <string.h>
static void print_reversed(const char *str, size_t len)
{
const char *ptr = str + len;
while (ptr > str)
putchar(*--ptr);
}
int main(int argc, char **argv)
{
for (int i = 0; i < argc; i++)
{
if (i != 0)
putchar(' ');
print_reversed(argv[i], strlen(argv[i]));
}
putchar('\n');
return 0;
}
There's no need to modify the strings; simply print the characters out one at a time in reverse order.
The logic is fairly straightforward: For each string in argv, reverse it and then print it.
#include <stdio.h>
#include <string.h>
void swap_characters(char *s, char *t) {
char tmp = *s;
*s = *t;
*t = tmp;
}
void reverse_string(char *s, int length) {
for (int i = 0; i < length / 2; ++i)
swap_characters(s + i, s + length - 1 - i);
}
int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
reverse_string(argv[i], strlen(argv[i]));
printf("%s ", argv[i]);
}
printf("\n");
}
Try this code give File name as reverse and put command line argument:-
There are lots of ways to do string reversal, and it is worth spending some time looking into because it is a standard interview question.
a simple implementation for null-terminated strings in C looks like
char * reverse(char * string){
int i;
int len = strlen(string);
for (i = 0; i < len/2; i++){
char c = string[i];
string[i] = string[len - i - 1];
string[len - i - 1] = c;
}
return string;
}
This version does manipulate the string, so we'll make a copy of the string just in case.
Once you have string reversal, you will need to run reverse on each argument, and print it out.
NOTE: arguments in a standard console application like this start with the name of the program as it was typed by the user. So if the program is invoked as ./my-program arg1 arg2, argv[0] will be "./my-program", so we will skip argv[0]
Using this, all you have to do is call reverse on each argument. like so
int main(int argc, char ** argv){
int i;
char * copy;
for ( i = 1; i < argc; i++){ // skip argv[0]
copy = strdup(argv[i]); // copy the string;
copy = reverse(copy);
printf("argv[%d] = \"%s\"\n", i, copy);
free(copy); // clean up the copy
}
}
All together, you get
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * reverse(char * string){
int i;
int len = strlen(string);
for (i = 0; i < len/2; i++){
char c = string[i];
string[i] = string[len - i - 1];
string[len - i - 1] = c;
}
return string;
}
int main(int argc, char ** argv){
int i;
char * copy;
for ( i = 1; i < argc; i++){ // skip argv[0]
copy = strdup(argv[i]); // copy the string;
copy = reverse(copy);
printf("argv[%d] = \"%s\"\n", i, copy);
free(copy); // clean up the copy
}
}
I have a program to reverse a string and convert it to uppercase. If I write helloworld!, the output must be !DLROWOLLEH. But if I write hello world! the output is !DLRO. Could you tell me where the possible problem is?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * reverse(const char * text)
{
if (text==NULL)
return NULL;
int length = strlen(text);
char * reversed_string = malloc(length+1);
for(int i = 0; i < length/2; ++i)
{
reversed_string[i] = text[(length-1) - i];
reversed_string[(length-1) - i] = text[i];
}
reversed_string[length] = '\0';
//upper(reversed_string);
return reversed_string;
}
void upper(char *str1)
{
while(*str1!='\0')
{
if(*str1>96&&*str1<123)
*str1=*str1-32;
str1++;
}
}
int main(int argc, char * argv[])
{
char p[256];
fgets(p, sizeof(p), stdin);
char * rev_str = reverse(p);
upper(rev_str);
printf("%s\n", rev_str);
rev_str = 0;
return 0;
}
The problem is here
for(int i = 0; i < length/2; ++i)
It length is an odd number (like 11 in your example), this will implicitly round down, and as a consequence, you never write to the middle element in the string. Un your case, this happened to be 0, but that is not guaranteed to be so, so any character might have appeared there, instead of terminating the string early.
The easiest fix would be changing that to (length+1)/2, but that will have the effect that you write the middle element twice.
Actually, I think it is much easier if you just reverse the string just by iterating over it in one direction instead of from both.
I've modified your code and it works as expected.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * reverse(const char * text)
{
if (text==NULL)
return NULL;
unsigned long length = strlen(text);
char * reversed_string = malloc(length+1);
for(int i = 0; i < length; ++i)
{
reversed_string[i] = text[(length-1) - i];
//reversed_string[(length-1) - i] = text[i];
}
reversed_string[length] = '\0';
//upper(reversed_string);
return reversed_string;
}
void upper(char *str1)
{
while(*str1!='\0')
{
if(*str1>96&&*str1<123)
*str1=*str1-32;
str1++;
}
}
int main(int argc, char * argv[])
{
char p[256];
fgets(p, sizeof(p), stdin);
char * rev_str = reverse(p);
printf("%s\n", rev_str);
upper(rev_str);
printf("%s\n", rev_str);
rev_str = 0;
return 0;
}
Since two hours, i'm trying to modify my program to give it arguments (argv) instead of a char.
So, here is my current code:
int i;
char ret[81];
*ret = 1;
for (i = 0; i < argc; i++)
{
ret[0] = '\0';
strcat(ret,argv[i]);
}
This code concatenate all args into a char, printf is returning the good same result as my old char argument, but not working in my code:
char test[] = "9...7....2...9..53.6..124..84...1.9.5.....8...31..4.....37..68..9..5.74147.......";
solve(test); //working
solve(ret); //not working
my app is launched like that:
./a.out "9...7...." "2...9..53" ".6..124.." "84...1.9." "5.....8.." ".31..4..." "..37..68." ".9..5.741" "47......."
Soooo, if anyone understand my problem i'll probably need some help :D
sample code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void solve(char *data){
static const char *result = "9...7....2...9..53.6..124..84...1.9.5.....8...31..4.....37..68..9..5.74147.......";
if(strcmp(result, data) == 0)
printf("working\n");
else
printf("not working\n");
}
int main(int argc, char *argv[]){
int i, total_length = 0;
for(i = 1; i < argc; ++i){
total_length += strlen(argv[i]);
}
char ret[total_length + 1];
ret[0] = '\0';
for(i = 1; i < argc; ++i){
strcat(ret, argv[i]);
}
char test[] = "9...7...."
"2...9..53"
".6..124.."
"84...1.9."
"5.....8.."
".31..4..."
"..37..68."
".9..5.741"
"47.......";
solve(test);
solve(ret);
return 0;
}