If you already answer this question, please skip, thanks C Programming. Fill in
ID: 3797222 • Letter: I
Question
If you already answer this question, please skip, thanks
C Programming. Fill in ...
This program will be called with one command line argument that
contains a string followed by an asterisk and an integer. Print
out the string as many time as indicated by the integer. For
example, when called as prog Hi*3, you print HiHiHi.
Hint: Look for the '*' starting from the back of the string.
len = strlen(arg) gives you the string length.
When you have found the '*', then arg + len + 1 is a pointer
to the integer that you can pass to atoi as in the preceding
exercise. Replace the '*' with a '' so you can print the
part that precedes it.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
int count = 1;
char* arg;
int len;
if (argc < 2) return -1;
arg = argv[1];
len = strlen(arg) - 1;
...
for (int i = 0; i < count; i++)
printf("%s", arg);
printf(" ");
return 0;
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* arg; int count = 0;
const char searchStr[2] = "*";
char *tokens; int inc=0, j;
char *strArray[3];
if (argc < 2) return 0;
arg = argv[1];
tokens = strtok(arg, searchStr); //-- split string with delimerter of '*' and create new array of string and int
while( tokens != NULL )
{
strArray[inc] = tokens;
tokens = strtok(NULL, searchStr);
inc++;
}
/*Find string array length*/
count = sizeof(strArray)/sizeof(strArray[0])-1;
if (count > 0 && strArray[0] != NULL && atoi(strArray[count-1]) > 0)
{
for (j=0; j<atoi(strArray[1]); j++)
{
printf("%s", strArray[0]);
}
}
printf(" ");
return 0;
}
Sample Output:
./a.out Hai*10
HaiHaiHaiHaiHaiHaiHaiHaiHaiHai
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.