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. - // 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.
16 4839
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..."
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.
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.
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.
I know about atoi to convert from a string to a number, but I haven't found anything about the reverse.
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: - 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"
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;
At first glance it looks to me like it should be
SS << myInt;
SS >> myStr;
Yes it should. Just a typo.
Yep. That's what I get for not actually having used the stringstream.
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. - // 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;
-
}
-
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 -
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;
-
}
-
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.
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.
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.
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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
by: Riku Jarvinen |
last post by:
Hi everyone,
I asked another question regarding this same subject about a week ago. See
thread:
...
|
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;
|
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...
|
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 )...
|
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. ...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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...
|
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...
|
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...
|
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,...
| |