suppose the user enters:
./Myfile blah1 blah2 blah3
I want to be able to read that in as:
blah1blah2blah3
IN ONE VARIABLE
Obviously I can print it out in one line excluding the white space, but I'm having trouble combining argv[1], argv[2], ....., argv [i]together!
This is what I tried, but I clearly have no clue what I'm doing, because it didn't work:
int main(int argc, char* argv[])
{
i = 1;
while(argv != NULL)
{
if(i > 1)
{
argv[1] = strncat(argv,argv[1],1000);
}
//printf("STRING LENGTH IS: %d", strlen(argv));
printf("%s\n\n", argv[1]);
i++;
}
}
Can someone help me out? I'm stuck on probably the easiest part of this assignment, because I don't know what to use to combine each argument! I've been trying to figure this out for hours...
Use the man pages, Luke.
char *strncat\(char *restrict s1, const char *restrict s2, size_t n\);
strcat(), strncat(), strlcat()
The strcat() function appends a copy of string s2, including
the terminating null character, to the end of string s1. The
strncat() function appends at most n characters. Each
returns a pointer to the null-terminated result. The initial
character of s2 overrides the null character at the end of s1.
You have your s1 and s2 interchanged, and the way it is written now,
you'll need to print argv[1] to get the final result.
As written, it also leaks memory, but that might not be an issue for you at this point.
[as each is copied, it allocates a new one and abandons the previous copy]
Thank you, that clears it up. Everything works now...
int main(int argc, char* argv[])
{
int i = 1;
for(i = 1; i < argc; i++)
{
if(i > 1)
{
argv = strncat(argv[i - 1],argv,1000);
}
printf("%s\n\n", argv);
}
printf("Printing string: %s\n", argv[i - 1]);
printf("The sentence entered is %u characters long.\n",strlen(argv[i - 1]));
return 0;
}