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;
}
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;
}
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
}
}
./a.out "1 23 5 7 2 21"
I want to convert the above string passed as a command line argument into an array of integers in C programming. Would really appreciate help.
Thank you.
A simple loop can solve your problem-
int a[argc];
for(i = 0; i < argc; i++)
{
a[i] = atoi(argv[i+1]);
}
If passing a string
./a.out "1 23 5 7 2 21"
You need to tokenize the string whilst passing the "int" value to an array (which should be dynamic) since you are passing a string and not multiple options. (Which was what I initially thought, but changed)
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* For strtok */
int main( int argc, char **argv )
{
int i = 0;
int *intArray;
const char s[2] = " ";
char *token;
token = strtok(argv[1], s);
intArray = malloc(sizeof(int));
while( token != NULL )
{
intArray[i++] = atoi(token);
token = strtok(NULL, s);
}
//intArray holds the values but this is to display the results
int j;
for (j=0; j < i ; j++){
printf( " %d\n", intArray[j] );
}
return 0;
}
If passing multiple options (after program name)
./a.out 1 23 5 7 2 21
int i;
int intArray[argc-1];
for (i=0; i < argc - 1; i++){
intArray[i] = atoi(argv[i+1]);
}
return 0;
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[]){
if(argc != 2){
exit(EXIT_FAILURE);
}
int n = 0;//number of elements
char prev = ' ', *s = argv[1];
while(*s){
if(isspace(prev) && !isspace(*s))
++n;
prev = *s++;
}
int nums[n];
char *endp;
s = argv[1];
for(int i = 0; i < n; ++i){
nums[i] = strtol(s, &endp, 10);
s = endp;
printf("%d\n", nums[i]);//check print
}
return 0;
}
The function makearg is supposed to count the number of words in a char array and also break each word up into their own spot in a pointer array.
Segmentation fault seems to be a problem with the strncpy function.
int makearg(char s[], char ***args);
int main(){
char **args = (char**)(malloc(100));
char *str = "ls is a -l file";
int argc;
argc = makearg(str, &args);
printf("%d", argc);
printf("%c", '\0');
int i;
for(i = 0; i < argc; i++){
puts(args);
printf("%c", '\n');
}
return 0;
}
/////////////////////////////////////////
int makearg(char s[], char ***args){
int argc = 0;
int charc = 0;
int wordstart = 0;
while(1){
if(s[charc] == '\0'){
strncpy(*args[argc], s + wordstart, charc - wordstart);
args[argc][(charc - wordstart) + 1] = '\0';
argc++;
break;
}
if(s[charc] == ' '){
strncpy(*args[argc], s + wordstart, charc - wordstart);
args[argc][(charc - wordstart) + 1] = '\0';
wordstart = charc + 1;
argc++;
charc++;
}
else{
charc++;
}
}
return argc;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int makearg(const char s[], char ***args);
int main(void){
char **args = NULL;
const char *str = "ls is a -l file";
int argc = makearg(str, &args);
printf("argc : %d\n", argc);
int i;
for(i = 0; i < argc; i++){
puts(args[i]);
free(args[i]);
}
free(args);
return 0;
}
int wordCount(const char *s){
char prev = ' ';
int wc = 0;
while(*s){
if(isspace(prev) && !isspace(*s)){
++wc;
}
prev = *s++;
}
return wc;
}
int makearg(const char s[], char ***args /*out*/){
int argc = wordCount(s);
int len;
if(argc == 0){
*args = NULL;
return 0;
}
*args = malloc(argc * sizeof(char*));
argc = 0;
while(1){
while(isspace(*s))
++s;
if(EOF==sscanf(s, "%*s%n", &len))
break;
(*args)[argc] = malloc(len + 1);
strncpy((*args)[argc], s, len);
(*args)[argc++][len] = '\0';
s += len;
}
return argc;
}
You allocated space for the args array of pointers, but you never allocate space for the strings you intend to store in them, so when you try to store the strings in makearg, you are interpreting whatever random garbage is there as a pointer, and that's not going to work.
Also, you only allocate 100 bytes for the pointer array -- it's not clear how many
words you expect to be able to split, but the malloc call should probably look more like
char **args = malloc(MAX_WORDS * sizeof(char *)); /* no cast required */
then follow that with a loop to do MAX_WORDS more malloc calls, in order to initialize args with valid pointers.
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. ;)