Thread: Help with Strings

  1. #1
    Master of Puppets rwmarsh's Avatar
    Join Date
    Feb 2006
    Location
    Texas
    Posts
    96

    Help with Strings

    I am trying to create a program using formatted output to the screen, two columns 15 characters wide, with the output being strings. If the string is longer than 15 characters I want to truncate it to fit in the column. So far this is what I have:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string mystring1="This is a string";
        string mystring2="This is another string";
        string tempstring="";
        cout<<setiosflags(ios::left);
        cout<<setw(17)<<"String 1"<<"String2\n";
        cout<<tempstring.assign(mystring1, 0, 15)<<"  ";
        tempstring="";
        cout<<tempstring.assign(mystring2, 0, 15)<<"\n";
        return 0;
    }
    This works, but I was wondering if there was a way to do it without the use of tempstring. Maybe a string member function?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What if you use:
    Code:
    cout << mystring1.substr(0, 15) << "  ";
    cout << mystring2.substr(0, 15) << "\n";
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Master of Puppets rwmarsh's Avatar
    Join Date
    Feb 2006
    Location
    Texas
    Posts
    96
    OK, That works great. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  4. damn strings
    By jmzl666 in forum C Programming
    Replies: 10
    Last Post: 06-24-2002, 02:09 AM
  5. menus and strings
    By garycastillo in forum C Programming
    Replies: 3
    Last Post: 04-29-2002, 11:23 AM