473,395 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

[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.

Expand|Select|Wrap|Line Numbers
  1. // exercise 2.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6.  
  7. using std::cout;
  8.  
  9. int main()
  10. {
  11.     int i;
  12.     for(i=0;i<=100;i++)
  13.         cout<<i<<"\t"<<i*i<<"\n";
  14.     system("PAUSE");
  15.     return 0;
  16. }
Thank you in advance.
Feb 11 '08 #1
16 4839
weaknessforcats
9,208 Expert Mod 8TB
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..."
Feb 11 '08 #2
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.
Feb 11 '08 #3
weaknessforcats
9,208 Expert Mod 8TB
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.
Feb 11 '08 #4
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.
Feb 11 '08 #5
I know about atoi to convert from a string to a number, but I haven't found anything about the reverse.
Feb 11 '08 #6
Ganon11
3,652 Expert 2GB
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:

Expand|Select|Wrap|Line Numbers
  1. int myInt = 1234;
  2. string myStr;
  3. stringstream SS;
  4. SS >> myInt; // Read a value into the stream
  5. SS << myStr; // Extract a value from the stream
  6. // Now myStr is "1234"
Feb 11 '08 #7
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;
Feb 14 '08 #8
weaknessforcats
9,208 Expert Mod 8TB
At first glance it looks to me like it should be
SS << myInt;
SS >> myStr;
Yes it should. Just a typo.
Feb 15 '08 #9
Ganon11
3,652 Expert 2GB
Yep. That's what I get for not actually having used the stringstream.
Feb 15 '08 #10
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.

Expand|Select|Wrap|Line Numbers
  1. // exercise 2.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <sstream>
  7. #include <iomanip>
  8.  
  9. using std::cout;        using std::stringstream;
  10. using std::string;        using std::setw;
  11.  
  12. int main()
  13. {
  14.     int i=0, max, width1, width2;
  15.     max=100;
  16.  
  17.     {stringstream store;
  18.     store<<max;
  19.     string size;
  20.     store>>size;
  21.     width1=size.length();
  22.     i=max*max;
  23.     store<<i;
  24.     store>>size;
  25.     width2=(size.length());
  26.     }
  27.  
  28.     for(i=0;i<=max;i++)
  29.         cout<<setw(width1)<<i<<setw(width2)<<i*i<<"\n";
  30.     system("PAUSE");
  31.     return 0;
  32. }
  33.  
Feb 17 '08 #11
Banfa
9,065 Expert Mod 8TB
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

Expand|Select|Wrap|Line Numbers
  1. int CountDigits(int number unsigned base)
  2. {
  3.     int count;
  4.  
  5.     if (base == 0) // Prevent divide by 0
  6.     {
  7.         return 0;
  8.     }
  9.  
  10.     for(count=1; number; count++)
  11.     {
  12.         number /= base;
  13.     }
  14.  
  15.     return count;
  16. }
  17.  
Feb 17 '08 #12
weaknessforcats
9,208 Expert Mod 8TB
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.
Feb 17 '08 #13
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.
Feb 17 '08 #14
whodgson
542 512MB
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.
Feb 19 '08 #15
Banfa
9,065 Expert Mod 8TB
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.
You can reuse a stringstream, however in doing so you need to reset it first before you try to use it call the method

stringstream::clear();

on your instance of the class before trying to reuse it.
Feb 19 '08 #16
Banfa
9,065 Expert Mod 8TB
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.
\t does not set the width to anything, it is a character and how it is handled normally depends on the terminal to which you send it.

Commonly the terminal moves the output cursor to the next column multiple of 8.
Feb 19 '08 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Matthew David Hills | last post by:
If setw() is being used to limit how many characters are pulled from a stream, should the # of characters taken from the stream depend on whether the stream is being sent to a std::string or a...
5
by: Riku Jarvinen | last post by:
Hi everyone, I asked another question regarding this same subject about a week ago. See thread: ...
2
by: tvn007 | last post by:
Below is my code: #include <string> #include <iostream> #include <iomanip> int main (void){ using namespace std; string name1 = "JOHN"; int id1 = 1234;
4
by: alternativa | last post by:
Hi, I'd like to obtain an output looking as follows: name number phone address Caroline 233 34234 White St. 12 Anna 929043 093284 Brown St. 325...
12
by: wickwire | last post by:
I have created a class and used it to further overload ostream: class drum { ... friend ostream& operator<< ( ostream&, drum const& ); } ostream& operator<< ( ostream& out, drum const& od )...
5
by: Petrakid | last post by:
Alright, so I asked earlier about this pig/chicken leg count thing and got some good help with it, thanks. I come to find out now that I do not supply just one number, but a range of numbers. ...
10
by: edd | last post by:
Hello all, I'm trying to put together some code that reads 3 adjacent pairs of hex digits from an istream. Each hex digit pair represents a non-negative integer. For example I would like to...
6
by: Rafael Olarte | last post by:
The goal of this project is to output the following information as follows: 34.5 38.6 4.1 42.4 3.8 close 46.8 4.4 big change. The values of the first colunm are obtain from a file...
11
by: Trent | last post by:
Running this I see that on first run, both bubble and selection sort have 9 sort counts while insertion sort has ZERO. With a sorted list, should this be ZERO for all? Also bsort and Ssort have...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.