C++ Questions

Pages: 1... 789101112
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//Chap 5: p179
//The Temperature Analyzer Program
#include<fstream>
#include<iomanip>
#include<iostream>
#include<sstream>
#include<string>
using namespace std;

int main()
{
	cout << "****** TEMPERATURE ALALYZER ******\n\n";

	string filename;
	ifstream inFile;
	while (true)
	{
		cout << "Enter filename: ";
		getline(cin, filename);

		inFile.open(filename);
		if (inFile)
			break;

		cout << "File \"" << filename << "\" does not exist, try again!\n\n";
	}
	cout << "File \"" << filename << "\" successfully opened!\n\n";

	unsigned int col1{ 7 };
	unsigned int col2{ 20 };

	cout
		<< setw(col1) << "LOW"
		<< setw(col1) << "HIGH"
		<< setw(col1) << "AVG\n";
	cout << "______________________________" << endl;
	cout << fixed << setprecision(1);

	double avg_total{ 0.0 };
	unsigned int lines_read{ 0 };
	unsigned int lines_success{ 0 };
	double temp_lowest = numeric_limits<double>::max();
	double temp_highest = numeric_limits<double>::lowest();

	string line;
	stringstream ss;
	while (getline(inFile, line))
	{
		double low{ 0.0 };
		double high{ 0.0 };
		double avg{ 0.0 };

		++lines_read;

		ss.str(line);
		ss.clear();

		if (ss >> low >> high)
		{
			++lines_success;
			avg = (low + high) / 2;

			cout 
				<< setw(col1) << low
				<< setw(col1) << high
				<< setw(col1) << avg << endl;

			avg_total += avg;

			temp_lowest = (temp_lowest < low) ? temp_lowest : low;
			temp_highest = (temp_highest > high) ? temp_highest : high;
		}
	}
	inFile.close();

	cout
		<< endl
		<< lines_success	<< " of "
		<< lines_read		<< " lines successfully processed.\n\n";

	double avg_daily = avg_total / lines_success;

	cout
		<< left	 << setw(col2)	<< "Lowest daily temp: "
		<< right << setw(col1)	<< temp_lowest << endl
		<< left	 << setw(col2)	<< "Highest daily temp: "
		<< right << setw(col1)	<< temp_highest << endl
		<< left  << setw(col2)	<< "Avg daily temp: "
		<< right << setw(col1)	<< avg_daily << endl << endl;
}


Thanks.

I save all my snippets of code in ONE rtf file and sometimes include output exactly like that. I was aware of the output block but not the "Somebody wrote:"...so that's how you fellas do that.

More annoyingly though is how someone preserves the spacing between code and right-sided comments succeeding the code? I align it nicely in code and in here it is all over the place in my other posts.

I rewrote the code without looking and added some of the suggestions.

1
2
ss.str("");
ss << line;


I've been meaning to ask this as well. What is the proper way to clear out the ss buffer above? Why wouldn't the above code work in place of that line below?

 
ss.str(line);
seeplus
This ones for you and your clever for's, not that I would use it but it was fun testing this eyesore.

1
2
3
4
5
6
7
8
9
10
	for (string filename{ "" }; cout << "Enter filename: ", getline(cin, filename);
		cout << "File \"" << filename << "\" does not exist, try again!\n\n")
	{
		inFile.open(filename);
		if (inFile)
		{
			cout << "File \"" << filename << "\" successfully opened!\n\n";
			break;
		}
	}
You don't need {""} for filename. The std::string default constructor provides this.

testing this eyesore

Beauty is in the eye of the beholder... :)
It is from Murach's C++ Programming 2018 (p159)


You might also like to consider the online learning resource:
https://www.learncpp.com/
Oh alright, I'll confess...I tried to make it look uglier.

Still not growing on me though...

1
2
3
4
5
6
7
8
9
10
	for (string filename; 
		cout << "Enter filename: ", getline(cin, filename);
		cout << "File \"" << filename << "\" does not exist, try again!\n\n")
	{
		if (inFile.open(filename), inFile)
		{
			cout << "File \"" << filename << "\" successfully opened!\n\n";
			break;
		}
	}



Another thing I've noticed is that this is ok after a cin>> to do this...
1
2
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');


But if you reverse the order, then you can run into problems with successive cin's once again.

1
2
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();


I will read through that eventually too.

I like this quote..."Becoming an expert won’t happen overnight, but with a little patience, you’ll get there."

But I will like to change that to "Becoming an expert won’t happen over MANY nights, but with TONS of patience you may one day think you are there, but then quickly get reminded that you are nowhere near and may even go running for a higher level language!"

PS, please stock up on keyboards as you might get inspired to pop quite a few!

Who owns this site? You know what would be a nice addition, a section with a beginner/med/adv leet type code that we get weekly assignments to start. Then we can all check on the other fancy ways of doing things.

Yes - because .ignore() fails if the stream isn't in a good state. .clear() ensures the state of the stream is good before .ignore().

I tried to make it look uglier.


You don't need L4 or L10

1
2
3
4
5
6
for (string filename; cout << "Enter filename: ", getline(cin, filename);
        cout << "File \"" << filename << "\" does not exist, try again!\n\n")
    if (inFile.open(filename), inFile) {
        cout << "File \"" << filename << "\" successfully opened!\n\n";
        break;
    }


Now you're cooking!
Yea, I figured as such it was failing cuz of errors...don't know if it is fair though and a better way it could have been done.

Yup, cooking up a new prescription for glasses!
Well you'll really like APL. This one line of code removes HTML tags from txt:

 
{⍵ /⍨ ~{⍵∨≠\⍵}⍵∊'<>'} txt


:) :)
how someone preserves the spacing between code and right-sided comments succeeding the code? I align it nicely in code and in here it is all over the place in my other posts


Do you use tabs or spaces for alignment? If you use tabs then the tab size needs to be the same as that used by this site. space alignment should be ok.

Who owns this site?


That's a very good question.... It hasn't been updated for quite a long time.
how [does] someone preserves the spacing between code and right-sided comments succeeding the code? I align it nicely in code and in here it is all over the place in my other posts.

I do it simply, in the VS IDE. I set the option that any tab is converted to spaces in code when pasted or formatted. So what I see in my editor is consistent with what I post here.

I set my tab and indent size to 3 for all languages.

I also have several extensions for aligning code on select features, = or multiple sets of one line code blocks for example.

Would you prefer reading code like this:
1
2
3
4
5
6
7
8
9
inline BOOL Sprite::GetZOrder( ) const { return m_zOrder; }
inline void Sprite::SetZOrder( LONG zOrder ) { m_zOrder = zOrder; }
inline void Sprite::SetBounds( RECT& bounds ) { CopyRect( &m_bounds, &bounds ); }
inline void Sprite::SetBoundsAction( BOUNDSACTION boundsAction ) { m_boundsAction = boundsAction; }
inline BOOL Sprite::IsHidden( ) const { return m_hidden; }
inline void Sprite::SetHidden( BOOL hidden ) { m_hidden = hidden; }
inline LONG Sprite::GetWidth( ) const { return m_bitmap->GetWidth( ); }
inline LONG Sprite::GetHeight( ) const { return m_bitmap->GetHeight( ); }
inline RECT& Sprite::GetCollision( ) { return m_collision; }

or this:
1
2
3
4
5
6
7
8
9
inline BOOL Sprite::GetZOrder( ) const                           { return m_zOrder; }
inline void Sprite::SetZOrder( LONG zOrder )                     { m_zOrder = zOrder; }
inline void Sprite::SetBounds( RECT& bounds )                    { CopyRect( &m_bounds, &bounds ); }
inline void Sprite::SetBoundsAction( BOUNDSACTION boundsAction ) { m_boundsAction = boundsAction; }
inline BOOL Sprite::IsHidden( ) const                            { return m_hidden; }
inline void Sprite::SetHidden( BOOL hidden )                     { m_hidden = hidden; }
inline LONG Sprite::GetWidth( ) const                            { return m_bitmap-> GetWidth( ); }
inline LONG Sprite::GetHeight( ) const                           { return m_bitmap-> GetHeight( ); }
inline RECT& Sprite::GetCollision( )                             { return m_collision; }


I most certainly prefer the 2nd, even if it is code I haven't seen before. Judicious use of whitespace is very helpful for reading comprehension.

When pasted into the editor here at CPlusPlus the second snippet doesn't look to be all neatly aligned. Preview or submit and the formatting is shown properly.

The code snippet is just a small piece of a much larger game engine spread across multiple C++ source and header files for WinAPI games using the Windows GDI. This code shows some of the methods for dealing with a sprite object.
A much less obnoxious code snippet from another part of the game engine that illustrates IMO the advantages of judicious application of whitespace:
289
290
291
292
g_guyMasterDelay = 50;
g_hits = 0;
g_misses = 0;
g_gameOver = FALSE;

vs.:
289
290
291
292
g_guyMasterDelay = 50;
g_hits           = 0;
g_misses         = 0;
g_gameOver       = FALSE;


Who owns this site?

An absentee landlord. Who in the recent past did some major work on the fora to give the place overall a "better" look. The rest of the site wasn't touched.

I actually prefer the legacy look of the site.

https://legacy.cplusplus.com

The owner is still paying the bills for site hosting and bandwidth usage, that ain't cheap, and occasionally looks in without announcing his presence.

Real life conspired to kidnap him from more active participation here.

As to getting the tutorial here up to date? That's a LOT of work and time expended, would you want to do it? I know I wouldn't even if I was much more knowledgeable about C++. I ain't, the bane of a self-taught programming hobbyist.

You'd be better off going to Learn C++. That site is actively maintained with frequent updates. There are no fora like here at CPlusPlus, though.

https://www.learncpp.com/

Learn C++ has been mentioned to you more than once. Hint, hint.
Last edited on
Yea, I figured as such it was failing cuz of errors.
Cruftin' bullet-proof code is a lot of work, writing and repeated testing.

Writing code that can deal with expected and unexpected problems is an ongoing effort.

Even code that appears to run and terminate without raising issues still might not be bug free.
seeplus
Those look like cave paintings. I use whatever it takes to align, so both.

George
I agree with spacing, 3 tabs is a good idea but can also get annoying when you have to go all the way to the right. Sometimes you gotta fight the VS IDE on your first or second try for spaces.

Maybe it should be the C++ motto...
C++ White spaces are your invisible friends!
C++ White spaces...the other white non-meat!
C++ Alignment is your ally!

Is that what you've been busy body'ing on, games? You know any OpenGL? Any games you put out there?

Anyone have any games out there we can check out?
I personally like to line things up too — it makes it so much easier to read.

But not everyone agrees. I once contributed code to a open source project where the structure itself was more clearly shaped by having, essentially, a visual table of what the code was doing. And took a 900 line procedure and turned it into something -significantly- shorter (under 150 lines, IIRC), using functionality the project itself provided!

The maintainer(s) of the project told me it was unreadable and that it didn’t conform to their coding standards and the thing I fixed was already under review anyway.

(It absolutely -did- conform to their coding standards — I had that document about memorized.)

I suspect the maintainer disliked me because I was brash about the update, lol, but lesson learned.

Anyway, the point is that I was bashed by a couple people who thought that simply lining up tabular data was an unreadable eyesore.

And they are absolutely entitled to that opinion, especially with their own project. Point is, be aware that there are a lot of competent and knowledgeable programmers who disagree about extraneous spacing.

Even if we can both agree they are Wrong™.
Any games you put out there?

"Funny" you should ask....

https://github.com/GeorgePimpleton/Win32-games

Not my games, just ones from two ooooooold Windows application programming interfaces (WinAPI) (when the API was known as Win32) books I've adapted to work with modern Windows. Using the antiquated Windows graphics device interface (GDI). The books are before C++11. The GDI was the Windows standard way to draw text and graphics.

The first "chapter" of the games is a C/C++/WinAPI primer.

WinAPI is also known as Windows Desktop programming.

The WinAPI can be intimidating, there are so many different data types used. And the amount of code needed to get a minimal GUI app can be quite a lot compared to a simple console mode app.

https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types

When 64-bit Windows was introduced a bunch of new data types were introduced.

https://learn.microsoft.com/en-us/windows/win32/winprog64/the-new-data-types

Well designed WinAPI code can and should compile for x86 and x64. VS can compile for both.

You know any OpenGL?

No. I know the GDI, I've mucked around with GDI+, DirectX2D, DirectX3D and the like.

I tried OpenGL years ago and at the time it kept being nothing but baskets of errors and lots of slow runtime code. OpenGL may be the defacto standard for other OSes other than Windows, but not for me.

There are newer, allegedly better because they can use newer GPUs if present, cross platform graphics setups available, Vulkan is one. Unity, Unreal and Cocos2d are others.

The last three are optional components available in Visual Studio, they need to be installed manually. Same as C++ has to be manually installed.
Sometimes you gotta fight the VS IDE on your first or second try for spaces.

In the VS IDE, Tools > Options > Text Editor > All Languages. I have the Tabs options set for

1. Block intending

2. tab and indent size to 3

3. insert spaces (replaces tab characters).

My Text Editor C/C++ Tab options are set the same.

In the C/C++ Code Style options there are a whole lot of Formatting options that can be set to prettify one's code. One nice feature of the options dialog is if you change the options you most times get a preview of what the change looks like.

I've tweaked out my VS with several extensions for formatting code to do things that VS won't do normally.
I personally like to line things up too — it makes it so much easier to read.

But not everyone agrees.

I prettify code to suit me first and foremost. If I glom code from others sources (here and other internet sites) one of the first things I do is reformat it so I have an easier time reading and hopefully be able to understand the code.

If someone else doesn't like how MY code looks, tough noogies. They can reformat to suit their likes.
Last edited on
Those look like cave paintings.
We've moved on from Dijkstra to Iverson.

This is Ken Iverson's 1979 Turing Award Lecture entitled Notation as a Tool of Thought. Add it to the required reading list next to Dijkstra from before:
https://www.jsoftware.com/papers/tot.htm
Last edited on
Pages: 1... 789101112