c - A program that, given a string, a width, and an empty string for ouput, centers the string in the ouput area. -
the function return 1 if formatting successful , 0 if errors, such string length greater width, found. i'm getting errors though? what's wrong? don't think i'm calling right either...
#include <stdio.h> int main() { int dummy, value = 0; formatstring(value); scanf_s("%d",&dummy); return 0; } int formatstring (char *in, char *out, int width) { //local declarations int spaces; char *start; char *walker; int value; spaces = (width – 1) – strlen(in); if (spaces < 0) { value = 0; } else { start = out + (spaces / 2); (walker = out; walker < start; walker++) *walker = ' '; strcpy (start, in); (walker = out + strlen(out); walker < out + width – 2; walker++) *walker = ' '; *walker = ‘\0’; } return value; }
your code ill-formed beyond recognition. homework solution looks this:
int str_center(char *out, int width, char *in) { int offset; // compute , check offset offset = (width - strlen(in)) / 2; if (offset < 0) return -1; // initialize output buffer memset(out, ' ', width - 1); out[width - 1] = '\0'; // write result memcpy(out + offset, in, strlen(in)); return 0; }
first, compute offset @ copy input string output string. negative iff input string strictly greater output string; in case, we'll bail out , return -1. developers use 0 success , non-zero failure, since there's 1 way succeed, thousands fail.
then, initialize output buffer spaces , terminate null terminator.
finally, using our offset write input string output string, starting @ desired position.
note don't need loop on of strings. memset()
, memcpy()
us, , maybe more efficient. note need 1 local variable. you're using 4 local variables such trivial function. try keep number of local variables small. if can't that, split function. otherwise, won't able read own code 2 weeks later. , judging result of efforts, you're having trouble reading immediately.
Comments
Post a Comment