Question

I have an assignment where I am required to output an array which contains information about songs. The problem I am having is formatting the output. My assignment specifies the length of each field that is displayed but I cannot find a good way to restrict the output. For example if a song title has 21 characters but is required to be 18, how would I keep it from going over the specified 18. I am using the setw() function to space everything correctly but it does not restrict output at all.

Was it helpful?

Solution

You can resize a c++ string using string::resize.

// resizing string
#include <iostream>
#include <string>

int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';

  unsigned sz = str.size();

  .resize (sz+2,'+');
  std::cout << str << '\n'; //I like to code in C++

  str.resize (14);
  std::cout << str << '\n';//I like to code
  return 0;
}

OTHER TIPS

You can get a substring with length 18 chars from the string and then output that.

http://www.cplusplus.com/reference/string/string/substr/

Example:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str="We think in generalities, but we live in details.";
  if(str.length()<=18) cout << str << endl;
  else cout << str.substr(0,15) << "..." << endl;
  return 0;
}

if you want original string to not be modified.

string test("http://www.cplusplus.com/reference/string/string/substr/");
string str2 = test.substr(0,18);
cout<<str2 <<endl;

If you don't need the rest of test anyway.

string test("http://www.cplusplus.com/reference/string/string/erase/");
test.erase(18);  // Make sure you don't go out of bounds here.
cout<<test<<endl;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top