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.
Asked
Active
Viewed 329 times
0
-
try just to limit the string to 18 chars maybe? – Jona Mar 24 '13 at 21:39
-
Are you using c++ string? or const char*s? – Mar 24 '13 at 21:40
-
Yes I am trying to limit one of the columns to 18 the others are different sizes, but if I can figure out one I can handle the rest. Also I am using a C++ string. – David tftyfy Mar 24 '13 at 21:45
-
Then I think you can use one of the answers here. – Mar 24 '13 at 21:54
3 Answers
0
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;
}

Johnny Mnemonic
- 3,822
- 5
- 21
- 33
0
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;
}

Jona
- 1,747
- 2
- 16
- 22
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;