Help with Strings

This is a discussion on Help with Strings within the C++ Programming forums, part of the General Programming Boards category; I am trying to create a program using formatted output to the screen, two columns 15 characters wide, with the ...

  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
    21,650
    What if you use:
    Code:
    cout << mystring1.substr(0, 15) << "  ";
    cout << mystring2.substr(0, 15) << "\n";
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 02:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 07: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21