• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ Help?

Status
Not open for further replies.

fenners

Member
Damn, my first recursive include problem. I have two header files, each of which needs access to the other, and I'm wracking my brain trying to figure out what I can modify.

Heh, that's a good interview question.

Common solution - move the interdependent functionality to a third header file you can include in both original headers... Doesn't need to be a shared class, just good old fashioned functions if it fits...

Usually, this is a sign of code/class design problems and it's a good time to rethink what you're encapsulating & what you're sharing/inheriting.
 
Damn, my first recursive include problem. I have two header files, each of which needs access to the other, and I'm wracking my brain trying to figure out what I can modify.

Foward declarations and get your implementation out of your headers.

foo.h:

class Bar;

class Foo { Bar* bar; };

bar.h:

class Foo;

class Bar { Foo* foo; };
 

BlueMagic

Member
Damn, my first recursive include problem. I have two header files, each of which needs access to the other, and I'm wracking my brain trying to figure out what I can modify.

This might help you. I don't know how good that site is (I'm pretty sure it's gonna get shit from some people here), but at least that article really helped me.
 

Zoe

Member
OT, but is there anyone here who could answer an ASP.NET/SSRS setup question? Or should I start up a thread?
 
EDIT: Never mind, figured it out! See bottom of post for what I did wrong.

Okay GAF, I need your help.

As part of an assignment, I have to read 1000 words from a file, and store all non-duplicates in an array. That's fine, got that done. Second part of the assignment, I have to setup a vector of pointers that points the address of each of the 1000 words to it's corresponding match in the array of strings.

For example, if I had:

blah
hello
hello
zippity
blah

The array wouldn't be storing duplicates:

blah
hello
zippity

But the vector would have pointers, for example, storing a pointer for the second hello pointing to the first hello. If that makes sense. So there ends up being about 200 values in the array, but 1000 pointers in the vector.

I can get it to work correctly in main, but that's a huge mess. I want to pass it to a function that can check for duplicates, and add the pointers to the vector as needed. I'm doing something very wrong with the passing the vector by reference, though, and I can't seem to figure out what it is. Go easy on me, I'm still pretty new to pointers, so I'm sure it's just something really stupid I'm doing.

Code:
bool checkDuplicates(string word, string *uniqueWords, vector <string*> &wordPtrs);

int main () {

     //Snipping out the stuff that's fine - reading the file, declaring vars and such
    for (int i = 0; i < 1000; i++) {
		inFile >> word;
		if(!checkDuplicates(word, uniqueWords, uniqueCount, &wordPtrs)) {
			uniqueCount++;
			uniqueWords[uniqueCount] = word;
		}
	}
     
     return 0;
}

bool checkDuplicates (string word, string *uniqueWords, int count, vector <string*> *wordPtrs) 
        {

	int count = 0;
	for (count = 0; count <=200; count++) {
		if (uniqueWords[count] == word) {
                        //This is where I error out
			wordPtrs.push_back(&uniqueWords[count]);
			return true;
		}
	}
	return false;
}

I get the error on the wordPtrs.push_back(&uniqueWords[count]) line. Specifically, VS says "Expression must have a class type."

So I assume it's because I'm just pointing to the address of the vector, and not actually creating the vector...right? Do I just need to define a new vector in checkDuplicates() that points to the same memory location as wordPtrs? Have I already passed it by reference correctly?

EDIT: Derp, just had to change it to this:

Code:
-snip-snip

if(!checkDuplicates(word, uniqueWords, totalWords, wordPtrs)) {
//snip snip


bool checkDuplicates (string word, string *uniqueWords, int totalWords, vector <string*>& wordPtrs) {
 
Back again with a C troubleshoot problem.

I'm still writing the code to sum of the integers 1- 10 and then find the average. I got the program to run but my arithmetic functions don't seem to work. They just spit out very large and random numbers. I can't tell what's wrong.

the code:

Code:
#include<stdio.h>
int main ()

{

	int i;
	int sum;
	float avg;
	sum = 0;
	avg = (sum/10.0);

	printf("What is the sum of the integers 1 through 10? What is the Average?\n");

       for (i = 0; i <= 10; i++)
	{
	sum = sum + i;
	}

printf("The sum of the integers 1 through 10 is %d, and the average is %d\n", &sum, &avg);

return 0;

}

and my output:

What is the sum of the integers 1 through 10? What is the Average?
The sum of the integers 1 through 10 is -281261224, and the average is -281261228
 

SteveMeister

Hang out with Steve.
You're calculating the average before you have the sum. Move that calculation after your for loop and before your printf.

Also, you're using %d to display avg, which is a float.. use %f.. And remove the &s before sum and avg in the printf. You're printing the addresses of the variables.
 
I have Head First and I like it because it's really easy to read, and they do a great job of explaining things without being too boring. Their examples are a little contrived though, but effective at getting the message across.
 

mt1200

Member
C++ complete noob here, haven't coded in this language since I was 17.

Our customer needs something that my employeer's SCADA software is incapable of doing, so I decided to write a small app and launch it from the windows task admin.

I have to read some MODBUS TCP registers containing date and time values ( in friendly integers). I thought that I was finishing the app because it works under virtual machines, but when I was about to test it in the real servers and PLCs, I found that it gets stuck forever trying to read data.

The TCP blocking is driving me nuts, what good books can you recommend me gaf?, MSDN examples are too hard to understand if you don't have years coding C++.

I couldn't understand the asynchronous socket mechanism, so I had to put the socket into its default mode ( blocking), and pass it the SO_RCVTIMEO parameter.
 

The Technomancer

card-carrying scientician
Heh, that's a good interview question.

Common solution - move the interdependent functionality to a third header file you can include in both original headers... Doesn't need to be a shared class, just good old fashioned functions if it fits...

Usually, this is a sign of code/class design problems and it's a good time to rethink what you're encapsulating & what you're sharing/inheriting.

Yup, that's what I ended up doing.
 
C++ complete noob here, haven't coded in this language since I was 17.

Our customer needs something that my employeer's SCADA software is incapable of doing, so I decided to write a small app and launch it from the windows task admin.

I have to read some MODBUS TCP registers containing date and time values ( in friendly integers). I thought that I was finishing the app because it works under virtual machines, but when I was about to test it in the real servers and PLCs, I found that it gets stuck forever trying to read data.

The TCP blocking is driving me nuts, what good books can you recommend me gaf?, MSDN examples are too hard to understand if you don't have years coding C++.

I couldn't understand the asynchronous socket mechanism, so I had to put the socket into its default mode ( blocking), and pass it the SO_RCVTIMEO parameter.

Unix Network Programming vol. 1 - W. Richard Stevens

Despite the name, this is just as relevant on Windows as it is on Unix. And on any operating system that supports BSD socket interface for that matter.

Keep in mind there is a difference between asynchronous and non-blocking. You mention MSDN, so i assume you're on Windows. The recommended Windows async i/o interface is called IO Completion Ports. It's complicated enough that I don't recommend it unless you are trying to achieve a high level of horizontal scalability (e.g. many, many, many clients connecting to one server), whereas in your case it sounds like you only need high performance in a single client/server setting. Basic non-blocking i/o should be sufficient in this case, which you can learn about in the Stevens book linked above.
 

Complex Shadow

Cudi Lame™
C++ gaf help me.

i have to do an assignment on stringstream

and i am kinda completely lost.

i don't know how about about attacking this.


this is my main.
Code:
double d1 = 12.3;
   int i1 = 45;
   SpyOutput spy(&cout);
   spy << "abc" << endl;
   spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;

i want to take whats in the cout and alter it.
 
C++ gaf help me.

i have to do an assignment on stringstream

and i am kinda completely lost.

i don't know how about about attacking this.


this is my main.
Code:
double d1 = 12.3;
   int i1 = 45;
   SpyOutput spy(&cout);
   spy << "abc" << endl;
   spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;

i want to take whats in the cout and and alter it.

Cant do that. What do you *really* want to do? Like what problem were you trying to solve by modifying the contents of stdout
 

Complex Shadow

Cudi Lame™
Cant do that. What do you *really* want to do? Like what problem were you trying to solve by modifying the contents of stdout

all i want to do is delete the space. and sup d1 with 12.3 and sub il with 45.



basically this is my output


Code:
abc
d1=12.3i1=45z

i really just don't know what to do because i have never dealt with stringstream before.
 

Windu

never heard about the cat, apparently
beginner question here

i need to add up a string of numbers (1+2+3+4 etc..) until they exceed 25,000 and then produce the sum and the last number added. I know how to add up integers till they reach a max and then give me the sum, but i don't know what to do here (i missed a class...)

here is what i have which isn't correct.
Code:
#include <iostream>
using namespace std;

int main()
{
	int sum = 0;
	int n;
	for (n = 1; n <= 25000 ;n = n + 1)
		sum = sum + n;
	cout << "the last number added was " << n << endl;
	cout << "the final sum was " << sum << endl;
	
	return 0;
}
 
Are you trying to find out what n+25000 = sum?, where n is the sum of the first 24999 terms?

Also you can change:
Code:
n =  n + 1

to:

Code:
n++

And you'll get the same result.
 

The Technomancer

card-carrying scientician
beginner question here

i need to add up a string of numbers (1+2+3+4 etc..) until they exceed 25,000 and then produce the sum and the last number added. I know how to add up integers till they reach a max and then give me the sum, but i don't know what to do here (i missed a class...)

here is what i have which isn't correct.
Code:
#include <iostream>
using namespace std;

int main()
{
	int sum = 0;
	int n;
	for (n = 1; n <= 25000 ;n = n + 1)
		sum = sum + n;
	cout << "the last number added was " << n << endl;
	cout << "the final sum was " << sum << endl;
	
	return 0;
}

Until the sum exceeds 25,000 or n exceeds 25,000? What you have currently runs until n exceeds 25,000
 

Feep

Banned
beginner question here

i need to add up a string of numbers (1+2+3+4 etc..) until they exceed 25,000 and then produce the sum and the last number added. I know how to add up integers till they reach a max and then give me the sum, but i don't know what to do here (i missed a class...)

here is what i have which isn't correct.
Code:
#include <iostream>
using namespace std;

int main()
{
	int sum = 0;
	int n;
	for (n = 1; n <= 25000 ;n = n + 1)
		sum = sum + n;
	cout << "the last number added was " << n << endl;
	cout << "the final sum was " << sum << endl;
	
	return 0;
}
If you mean until the SUM exceeds 25,000, you'll need to use a while loop. Remember, for loops are for when you know beforehand how many times the loop will be run. Otherwise, use the more flexible while loop, which will continue to do something until a specific condition is reached.
 

Windu

never heard about the cat, apparently
Are you trying to find out what n+25000 = sum?, where n is the sum of the first 24999 terms?

Also you can change:
Code:
n =  n + 1

to:

Code:
n++

And you'll get the same result.
no from my understanding its supposed to be adding up 1+2+3 etc..until it exceeds 25,000.

like adding 1+2+3 till it exceeds 5 and then telling me that the sum is 6 and the last number added was 3.
 

The Technomancer

card-carrying scientician
no from my understanding its supposed to be adding up 1+2+3 etc..until it exceeds 25,000.

like adding 1+2+3 till it exceeds 5 and then telling me that the sum is 6 and the last number added was 3.

Right, the "it" you keep referring to is the sum, not the "n". Like feep said, you want to use a "while" loop that goes until the sum exceeds 25,000
 

Spoo

Member
Just use an accumulator:

int accum = 0;

for (int i = 0; accum < 25000; ++i)
accum += i;

edit: I may be mis-reading what is needed.
 

KorrZ

Member
New to programming myself, just started learning this month but, couldn't he just thrown in a:

Code:
 	for (n = 1; n <= 25000 ;n++){
		sum = sum + n;
		[B]if (sum >= 25000)
		break;[/B]
	}

to get the same effect?
 

Ecrofirt

Member
beginner question here

i need to add up a string of numbers (1+2+3+4 etc..) until they exceed 25,000 and then produce the sum and the last number added. I know how to add up integers till they reach a max and then give me the sum, but i don't know what to do here (i missed a class...)

here is what i have which isn't correct.
Code:
#include <iostream>
using namespace std;

int main()
{
	int sum = 0;
	int n;
	for (n = 1; n <= 25000 ;n = n + 1)
		sum = sum + n;
	cout << "the last number added was " << n << endl;
	cout << "the final sum was " << sum << endl;
	
	return 0;
}

Is it not correct because your sum gets way too high? That seems like the only problem.

Why not just do an if as follows

if (sum > 25000)
{
break;
}

below your cout statement?
 

The Technomancer

card-carrying scientician
New to programming myself, just started learning this month but, couldn't he just thrown in a:

Code:
 	for (n = 1; n <= 25000 ;n++){
		sum = sum + n;
		[B]if (sum >= 25000)
		break;[/B]
	}

to get the same effect?
You could, but then the "n <= 25000" part isn't really needed. A while loop is more elegant.
 

Slavik81

Member
C++ gaf help me.

i have to do an assignment on stringstream

i want to take whats in the cout and alter it.

std::cout is not an std::stringstream. I don't understand what you're asking.

std::stringstream is a class that inherits from istream and ostream.
std::cout is an ostream object. It is not an istream, or a stringstream.
 

KorrZ

Member
You could, but then the "n <= 25000" part isn't really needed. A while loop is more elegant.

So a while loop would be more of a good habit/optimization kinda thing? I haven't gotten past console applications yet so the book I'm using hasn't focused too strongly on optimization yet.
 
Speaking of console applications, how big is the jump from making console applications to actual windows applications? I only ask because I'm in my second semester of the comp sci program and we're doing adts, classes, trees, recursion, etc. and just wondered, after learning memory management and dealing with data types and what not, what else do I need to know?

Primarily because I know I'll have some free time and I'd like to start toying with android and ios development and other random projects.
 
So a while loop would be more of a good habit/optimization kinda thing? I haven't gotten past console applications yet so the book I'm using hasn't focused too strongly on optimization yet.

For something like this, yes. You usually think of using for loops when you want to something some x number of times. Think of it as like "I want to do this for this many times".

A while loop would be more appropriate here because you're saying something like "I want to keep doing this while this is the case".

so you would have something like:
Code:
int i = 1;
int sum = 0;
while(sum < 25000) {
	sum += i++;
}
 

Zoe

Member
Speaking of console applications, how big is the jump from making console applications to actual windows applications? I only ask because I'm in my second semester of the comp sci program and we're doing adts, classes, trees, recursion, etc. and just wondered, after learning memory management and dealing with data types and what not, what else do I need to know?

Primarily because I know I'll have some free time and I'd like to start toying with android and ios development and other random projects.

You'll need to learn UI stuff. It's not difficult, but I would have never learned it in school if I hadn't taken a throw-away 1 credit class.
 

tokkun

Member
So a while loop would be more of a good habit/optimization kinda thing? I haven't gotten past console applications yet so the book I'm using hasn't focused too strongly on optimization yet.

Not really. Just use whichever style you prefer. As luoapp has shown, the for loop version can be more more compact. Some people might argue that because the while loop is more verbose it's easier to read and understand. Both versions are likely to compile to the same thing.
 

Complex Shadow

Cudi Lame™
std::cout is not an std::stringstream. I don't understand what you're asking.

std::stringstream is a class that inherits from istream and ostream.
std::cout is an ostream object. It is not an istream, or a stringstream.
ill try to explain it better once i get off my coffee high.
but basically, here is my main.
Code:
void main()
{
   double d1 = 12.3;
   int i1 = 45;
   SpyOutput spy(&cout);
   spy << "abc" << endl;
   spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;
}
and output.
Code:
abc
d1=12.3 i1=45z

and i have to use stringstream in the class spyoutput.

honestly thats all i can tell you. i know i am being vague. and i am sorry. but thats why i am asking gaf. its not like i ve put this assignment off till the last min. but my prof (nice guy) assumes i know this from my previous class. when all i did in my previous class was draw sidways triangles (not really, but its kinda a haze).
 

Godslay

Banned
So a while loop would be more of a good habit/optimization kinda thing? I haven't gotten past console applications yet so the book I'm using hasn't focused too strongly on optimization yet.

They both (while and for) run in O(n) time. So they should be very similar in terms of how fast they run. I tested both in Java and they are identical in milliseconds when summing up to 25000.
 

Bruiserk

Member
I have an issue. I don't want to post the code on here, so I have linked it to pastebin.

http://pastebin.com/QgVaTJe7

My problem is within this part:

Code:
double find_sum() {
  if(numbers.size() != 0) {
    for(unsigned int i = 0; i < numbers.size(); ++i) {
      sum = sum + numbers[i];
      return sum;
    }
  } else{
    error("You haven't entered any numbers.");
    return 0;
  }
}

My compiler gives me this error:

a2q6.cpp: In function ‘double find_sum()’:
a2q6.cpp:85:1: error: control reaches end of non-void function [-Werror=return-type]
cc1plus: all warnings being treated as errors
 

Slavik81

Member
The compiler isn't smart enough to know you covered every possible branch like that. There is an error in the main part of your if statement. Fix that and you solve both issues.
 

Lathentar

Looking for Pants
I have an issue. I don't want to post the code on here, so I have linked it to pastebin.

http://pastebin.com/QgVaTJe7

My problem is within this part:

Code:
double find_sum() {
  if(numbers.size() != 0) {
    for(unsigned int i = 0; i < numbers.size(); ++i) {
      sum = sum + numbers[i];
      return sum;
    }
  } else{
    error("You haven't entered any numbers.");
    return 0;
  }
}

My compiler gives me this error:
Move the "return sum;" outside of the for loop. That will solve the compile error and the bug in your program!
 

Slavik81

Member
ill try to explain it better once i get off my coffee high.
but basically, here is my main.
Code:
void main()
{
   double d1 = 12.3;
   int i1 = 45;
   SpyOutput spy(&cout);
   spy << "abc" << endl;
   spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;
}
and output.
Code:
abc
d1=12.3 i1=45z

and i have to use stringstream in the class spyoutput.

honestly thats all i can tell you. i know i am being vague. and i am sorry. but thats why i am asking gaf. its not like i ve put this assignment off till the last min. but my prof (nice guy) assumes i know this from my previous class. when all i did in my previous class was draw sidways triangles (not really, but its kinda a haze).

I don't see why you need stringstream. Overload SpyOutput& operator<<(std::string&) const and modify the data passed into it before forwarding it on to cout.
 

Lathentar

Looking for Pants
I don't see why you need stringstream. Overload SpyOutput& operator<<(std::string&) const and modify the data passed into it before forwarding it on to cout.

I imagine he needs to delay outputting to the output stream he's passing to SpyOutput until SpyOutput destructs.

So you could have a stringstream has a member of the SpyOutput class, overload the << operator for strings, doubles and ints and have it write to the stringstream. Then on destruction of the SpyOutput class, do myDelayedOStream << myStringStream.str();
 

Slavik81

Member
Speaking of console applications, how big is the jump from making console applications to actual windows applications? I only ask because I'm in my second semester of the comp sci program and we're doing adts, classes, trees, recursion, etc. and just wondered, after learning memory management and dealing with data types and what not, what else do I need to know?

Primarily because I know I'll have some free time and I'd like to start toying with android and ios development and other random projects.

Modern frameworks are not hard to learn, though the paradigm is different. However, raw Win32 and some of the other old APIs are very complex and difficult.

I'm sure iOS and Android have good tools available for them, though I've never done mobile development myself. Play around and I'm sure you'll learn lots of useful stuff.
 

RiZ III

Member
Speaking of console applications, how big is the jump from making console applications to actual windows applications? I only ask because I'm in my second semester of the comp sci program and we're doing adts, classes, trees, recursion, etc. and just wondered, after learning memory management and dealing with data types and what not, what else do I need to know?

Primarily because I know I'll have some free time and I'd like to start toying with android and ios development and other random projects.

Writing an actual application can become a giant mess really fast if you don't plan it out and architect it right. When you learn any API, the first few attempts will be mostly throw away code as it will mostly be a learning experience. Once you understand how it works, then you can design the framework. Most of my win32 apps were pretty poorly written until I actually designed a framework that was API independent. It forces you have uncluttered code add, one that separates the API calls from the actual app.
 
ill try to explain it better once i get off my coffee high.
but basically, here is my main.
Code:
void main()
{
   double d1 = 12.3;
   int i1 = 45;
   SpyOutput spy(&cout);
   spy << "abc" << endl;
   spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;
}
and output.
Code:
abc
d1=12.3 i1=45z

and i have to use stringstream in the class spyoutput.

honestly thats all i can tell you. i know i am being vague. and i am sorry. but thats why i am asking gaf. its not like i ve put this assignment off till the last min. but my prof (nice guy) assumes i know this from my previous class. when all i did in my previous class was draw sidways triangles (not really, but its kinda a haze).

What is the actual assignment? Can you just post the full text of the assignment?

So you have this main function. I have no idea what it's purpose is or what the purpose of the original program is, so there's really no way to provide any advice. In the main function, it looks like you're trying to print some text and numbers for an unknown reason.

Then you say something about wanting to "replace" the numbers with something else, but I don't even know what that means. Without a complete statement of the problem I'm just really not sure what to tell you I guess.
 

Complex Shadow

Cudi Lame™
What is the actual assignment? Can you just post the full text of the assignment?

So you have this main function. I have no idea what it's purpose is or what the purpose of the original program is, so there's really no way to provide any advice. In the main function, it looks like you're trying to print some text and numbers for an unknown reason.

Then you say something about wanting to "replace" the numbers with something else, but I don't even know what that means. Without a complete statement of the problem I'm just really not sure what to tell you I guess.


quote to reveal link

 
quote to reveal link


Ok nooooow we're getting somewhere.

First some background.

One of stringstream's functions is to basically replace the C-style functionality of printf / scanf if you're familiar with that. In C, printf is for output and scanf is for input. In C++, there are istreams (for input), ostreams (for output), and iostreams (for both input and output). std::stringstream is an iostream. cout is an ostream.

The ostream cout is "backed by" your console's output window, in a manner of speaking. That means when you "write to" cout, the resulting string is displayed on your screen. You can't access it anymore and you can't change it. It's gone.

The iostream std::stringstream is backed by an actual string object. That means you write to an std::stringstream and you don't see anything, except that the text of whatever you put in it is stored in a string for you to do whatever you want with.

Because std::stringstream supports both input and output, and because it is backed by an actual string object, it provides a convenient way to do conversions between strings and numbers. Here's a very short snippet of code that converts a string to a double.

std::stringstream foo;
double d;
foo << "12.6"; //The backing string now contains the text "12.6", no conversion necessary
foo >> d; //The backing string is converted into a double, and d = 12.6 now.

Here's a short snippet of code that converts the other way.

std::stringstream foo;
std::string str;
foo << 12.6 //The backing string now contains the text "12.6", double->string conversion
foo >> str; //No conversion necessary, the backing string is simply copied into 'str'.

So basically, for your assignment, every single time your << operator is called, you need to:

a) create an std::stringstream
b) Write your argument into it
c) convert it to a temporary string
d) compute the arithmetic sum of all characters in that string and store it in a class member variable so that you're keeping a running tally
e) also keep a running tally of the total number of characters you've encountered so far.

Does this make sense at all?
 

Complex Shadow

Cudi Lame™
Yea. Well kind of but that's because it's currently 3 am and I feel sick. I'll look more into this in morning. But thank you so much for all your help. I know I sound a little winny atm. But that's because I am stressing out. I am sure once I feel better i'll start to get it. But thank you for helping me even though I was being so werid.
 
Status
Not open for further replies.
Top Bottom