I need to read from user some text and then print out the same text, with "
at the beginning and "
at the end of the string. I used getline
to read a whole line (with spaces too).
Example (what I should get):
User writes: hello
I need to print: "hello"
Example (what Im getting):
User writes: hello
My app prints: "hello
"
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun(int times)
{
int i = 0, j = 255;
char *str = malloc(sizeof(char) * j);
char *mod = malloc(sizeof(char) * j);
for(i=0; i<j; i++)
mod[i] = 0;
i = 0;
while(i<times)
{
printf("\n> ");
getline(&str, &j, stdin);
strcpy(mod, "\"");
strcat(mod, str);
strcat(mod, "\"");
printf("%s\n", mod);
i ++;
}
free(mod);
mod = NULL;
free(str);
str = NULL;
}
int main(int argc, char **argv)
{
fun(4);
return 0;
}
SOLVED:
Hah, it was easy .. But can it be done EASIER?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fun(int times)
{
int i = 0, j = 255;
char *str = malloc(sizeof(char) * j);
char *mod = malloc(sizeof(char) * j);
for(i=0; i<j; i++)
mod[i] = 0;
i = 0;
while(i<times)
{
printf("\n> ");
getline(&str, &j, stdin);
int s = strlen(str);
strcpy(mod, "\"");
strcat(mod, str);
mod[s] = 0;
strcat(mod, "\"");
printf("%s\n", mod);
i ++;
}
free(mod);
mod = NULL;
free(str);
str = NULL;
}
int main(int argc, char **argv)
{
fun(4);
return 0;
}