The overall width of the line is 20 characters. How can I center a string using print so that
title becomes
space-title-space
i have something like this so far
Code:fprintf(myfile, "%20s\n",mystring);
The overall width of the line is 20 characters. How can I center a string using print so that
title becomes
space-title-space
i have something like this so far
Code:fprintf(myfile, "%20s\n",mystring);
Last edited by oceans; 07-23-2014 at 12:28 AM.
Do a simple calculation. For example, "title" has a length of 5, so there must be 15 spaces. Therefore, to centre the text, you should insert (15 / 2) = 7 spaces (or 8, if you prefer to round up).
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
>> Therefore, to center the text, you should insert (15 / 2) = 7 spaces
Don't forget that the field-width needs to include the length of the string - since it's in the field.
ggCode:#include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef _WIN32 #include <Windows.h> int GetColumnWidth() { CONSOLE_SCREEN_BUFFER_INFO info; HANDLE out; if (!(out = GetStdHandle(STD_OUTPUT_HANDLE)) || !GetConsoleScreenBufferInfo(out, &info)) return 80; return info.dwSize.X; }//GetColumnWidth #else int GetColumnWidth() {return 80;} #endif int main() { const char *s = "Hey, I'm centered!"; const int total_width = GetColumnWidth(); const int s_width = strlen(s); const int field_width = (total_width - s_width) / 2 + s_width; printf("%*s\n", field_width, s); return 0; }//main