[c++]Question about setw

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Simonius
    New Member
    • Feb 2008
    • 47

    [c++]Question about setw

    Hello,

    I'm teaching myself C++ with Accelerated C++ by Andrew Koenig.

    I'm having a small problem with an exercise at page 73.

    Write a program to calculate the squares of int values up to 100. The program should write two columns: The first list the value; the second contains the square of that value. Use setw(described above) to manage the output so that the values line op in columns.
    Now I was wondering how I should do that with setw, easiest way seems to somehow get how many characters my counter is, and then set setw for the first part to that length+1.

    The second thing I'm wondering about is: why use setw and not just \t in this case.

    This is what I wrote as solution with \t but I'd like to solve it with setw since that's the question.

    Code:
    // exercise 2.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    
    using std::cout;
    
    int main()
    {
    	int i;
    	for(i=0;i<=100;i++)
    		cout<<i<<"\t"<<i*i<<"\n";
    	system("PAUSE");
    	return 0;
    }
    Thank you in advance.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    It says "two colunns" so I don't know why \t isn't OK.

    What was your problem in using setw??

    BTW: system("PAUSE") at the end of your program is not required. With Visual Studio.NET, execute your program using "Start without Debugging". The program will pause at the end of main() with "Press any key to continue..."

    Comment

    • Simonius
      New Member
      • Feb 2008
      • 47

      #3
      The problem I'm having is determening the length of the integer.

      Either I use a left allign and use a width of the ammount of digits of the largest counters +1.

      Or I use a right allign of the ammount of digits of the largest result + 1.

      But I don't know how to get how many digits the number is.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Have you considered inserting the integer in a stringstream and recovering it as a string?? That way string::size() would be the number of characters in the integer.

        Comment

        • Simonius
          New Member
          • Feb 2008
          • 47

          #5
          I would insert it into a string if I know how to convert from string to int and from int to string for the first time.
          A follow up question is to adapt it to another number.

          The book hasn't shown that much yet.

          Comment

          • Simonius
            New Member
            • Feb 2008
            • 47

            #6
            I know about atoi to convert from a string to a number, but I haven't found anything about the reverse.

            Comment

            • Ganon11
              Recognized Expert Specialist
              • Oct 2006
              • 3651

              #7
              Well, the reverse of int atoi(char*) is simply char* itoa(int), but these are both legacy C functions that should be avoided in C++. A stringstream will act like a stream (that's cin and cout) that can take your number and spit out a string, or vice versa, like this:

              [CODE=cpp]int myInt = 1234;
              string myStr;
              stringstream SS;
              SS >> myInt; // Read a value into the stream
              SS << myStr; // Extract a value from the stream
              // Now myStr is "1234"[/CODE]

              Comment

              • Simonius
                New Member
                • Feb 2008
                • 47

                #8
                Hello, sorry for the late response but I've been quite busy.

                Which libraries & namespaces do I need for your example?

                And I could be mistaken due to not having tested it yet and not having worked with streams yet but didn't you switch the >> and <<?

                At first glance it looks to me like it should be
                SS << myInt;
                SS >> myStr;

                Comment

                • weaknessforcats
                  Recognized Expert Expert
                  • Mar 2007
                  • 9214

                  #9
                  Originally posted by Simonius
                  At first glance it looks to me like it should be
                  SS << myInt;
                  SS >> myStr;
                  Yes it should. Just a typo.

                  Comment

                  • Ganon11
                    Recognized Expert Specialist
                    • Oct 2006
                    • 3651

                    #10
                    Yep. That's what I get for not actually having used the stringstream.

                    Comment

                    • Simonius
                      New Member
                      • Feb 2008
                      • 47

                      #11
                      Question, can a stringstream only be used once?
                      Because while the following code seems ok to me, setw2 also equals 3 while it should be 5.
                      I've run the program partially to before width2=.. to check where the error is and size seems to stay 100 while it should turn 100000.

                      Code:
                      // exercise 2.cpp : Defines the entry point for the console application.
                      //
                      
                      #include "stdafx.h"
                      #include <iostream>
                      #include <sstream>
                      #include <iomanip>
                      
                      using std::cout;		using std::stringstream;
                      using std::string;		using std::setw;
                      
                      int main()
                      {
                      	int i=0, max, width1, width2;
                      	max=100;
                      	
                      	{stringstream store;
                      	store<<max;
                      	string size;
                      	store>>size;
                      	width1=size.length();
                      	i=max*max;
                      	store<<i;
                      	store>>size;
                      	width2=(size.length());
                      	}
                      
                      	for(i=0;i<=max;i++)
                      		cout<<setw(width1)<<i<<setw(width2)<<i*i<<"\n";
                      	system("PAUSE");
                      	return 0;
                      }

                      Comment

                      • Banfa
                        Recognized Expert Expert
                        • Feb 2006
                        • 9067

                        #12
                        Originally posted by weaknessforcats
                        Have you considered inserting the integer in a stringstream and recovering it as a string?? That way string::size() would be the number of characters in the integer.
                        That seems like a rather conveluted way to me when a simple for loop dividing by the base you are interested in until you read 0 would achieve the same thing

                        [code=cpp]
                        int CountDigits(int number unsigned base)
                        {
                        int count;

                        if (base == 0) // Prevent divide by 0
                        {
                        return 0;
                        }

                        for(count=1; number; count++)
                        {
                        number /= base;
                        }

                        return count;
                        }
                        [/code]

                        Comment

                        • weaknessforcats
                          Recognized Expert Expert
                          • Mar 2007
                          • 9214

                          #13
                          Yes, that works but only for an int. If a double were entered, you will need to do something else to get the number of characters in the double.

                          Comment

                          • Simonius
                            New Member
                            • Feb 2008
                            • 47

                            #14
                            weaknessforcats am I doing something wrong in my code because I can't find anything about a stringstream only being capable of being used once.

                            Comment

                            • whodgson
                              Contributor
                              • Jan 2007
                              • 542

                              #15
                              Doesn`t `setw` set the width of the column to which the data is printed?; whereas \t sets the width of the column separating the 2 data columns.
                              e.g.
                              cout<<setw(3)<< i<<"\t"<<setw(5 )<<i*i<<"\n"; //might keep the data columns tidier.

                              Comment

                              Working...