• 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.
:lol, yes, that's a crucial piece of information. I probably should've asked that first.

You might be able to run it with whatever the Mac version of WINE is, but no guarantees.
 
As you can tell, I'm new at this.

Since C++ is compiled, you have to build it with a compiler for the target architecture/OS. Most easily this is done by compiling the source code on the target computer (or one like it). If she's got a Mac, compile your code using g++ on her Mac.


I'll see if I can get her to install WINE.

That's a lot of work.

Why is this even a program and not a document? .html/.doc/.pdf/.txt, etc?

If you want to flex your programming muscles, use an interpreted language that the Mac already has installed, like Perl, Python, PHP, or continue to use a command line program like that and compile the source code on the Mac, won't take long.

Edit: copied your source code verbatim into foo.cpp:
Code:
workmac:~ crudediatribe$ g++ foo.cpp 
workmac:~ crudediatribe$ ./a.out 
--------------------------------------------------------------------------------
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
|                                                                              |
--------------------------------------------------------------------------------

^C
workmac:~ crudediatribe$


Use vim plus g++?
This would likely also require packaging custom DLLs in a Windows environment.

On the Mac.
 

TheBez

Member
Code:
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>

using namespace std;

int stripWhite(char *str); 


int main()
{
	char str[100];

	
	
	cout << "Enter a sentence and I will delete all spaces in it" << endl;
	cin.getline(str,100);
	int count = stripWhite(str);
	cout << count << " white spaces were removed" << endl;
	cout << "The string without spaces in it is:  " << str << endl;

return 0;
}

int stripWhite(char *str)
{
int i = 0; 
int j = 0;
while(str[i] != '\0')
{
	if(str[i] == ' ')
	j++;
		str[i] = '.' ;
	
	i++;
}

return j;
}

So my assignment is using pointers write a function called stripWhite that will strip all of the white spaces from an array of characters. Your function should return the number of white spaces that you deleted. Your output should look something like the following:

Enter a sentence and I will strip out all spaces.
The quick brown fox jumped over the lazy old dog
Your sentence without spaces is:
Thequickbrownfoxjumpedoverthelazyolddog.

I have that so far which is working to return the number of blank spaces but returning the string as "....................." rather than something proper. Any ideas GAF?
 
D

Deleted member 30609

Unconfirmed Member
edit: oh, if the returned number is fine, it's the if block.
 

tokkun

Member
Err yes I'm, I don't know what to put in between the ' ' to close the space because my compiler wont simply accept ''

Yeah, you can't do that in C++. A C string is an array of characters, so you can't just cut one out; you would have to shift down every subsequent character.

I suggest that you don't try to do this in-place - that is, don't use the same string for input and output. Create a 2nd string for output. That should make it easier for you to figure out what to do.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
'' is not a valid char.

cstrings are tricky to manipulate, you can't just remove a char because you'll need something to fill in the array.

If the sentence looked like:
[q][c][k][ ][r][o][w][n]

You can't just turn it into:
[q][c][k][r][o][w][n]

You'll need to move every char in the word brown one space back, or copy chars from the input into a new array while ignoring all ' ' chars.
 

Boss Man

Member
Err yes I'm, I don't know what to put in between the ' ' to close the space because my compiler wont simply accept ''
Think of an array the way Haly posted:
If the sentence looked like:
[q][c][k][ ][r][o][w][n]

Where each [ ] is a place in memory that holds data that we're seeing as characters, like 'q', 'u', or ' '.
The idea of changing one of those values to '', to simply skip that block, is not the correct way to be thinking about an array (nor is it a valid value for a character).


Here's an easy solution without doing anything clever:

Iterate through the array.
Count the blank spaces. (and store the count)


Make a separate array of size (old array size - number of blank spaces).

Iterate through the old array again.
If the character is not a blank space, put it into the other array.
If the character is a blank space, don't put it in the other array.

Your new array is the old string minus blank characters. You can clear out the old array and swap the new one into it.


If you want to avoid creating a new array, you're just going to have to slide the characters over a spot each time you encounter a blank space.

Something like:

for( i=0 ; size-1; i++ )
if( blank space )​
for( j=i; size-2; j++ )​
s[j] = s[j+1]​


I haven't messed with C++ in a little bit, so I don't know if it will complain about any of this or not tbh. You may need to look into the memory allocation functions. I'm assuming that there won't be a problem with 'run-off' spots in the array because the null character is going to be following at the tail, but I dunno.
 

Slavik81

Member
Not sure but wouldn't str = str[i+1] work? And replace null with the last character.

No, you need to think about the next time around the loop. It's possible to do this, but +1 is too rigid. The number of steps over you have to take depends on the number of characters removed.
 

maharg

idspispopd
Code:
void remove_match_in_place(char *str, char match)
{
    for (char *next = str; *next != 0; next++)
    {
        *str = *next;
        if (*next != match) str++;
    }
    *str = 0;
}

Wee.
 

2real4tv

Member
No, you need to think about the next time around the loop. It's possible to do this, but +1 is too rigid. The number of steps over you have to take depends on the number of characters removed.

Yes your right. I was always a terrible programmer used alot of trial and error.
 

Window

Member
Are there any specific resources (books or online teaching programs) you guys would recommend for learning C++? It is pretty essential to my degree but I won't get to cover it in my course since I've already progressed past that year and the Uni just recently updated their syllabus which only applies to new students.
 

maharg

idspispopd
Are there any specific resources (books or online teaching programs) you guys would recommend for learning C++? It is pretty essential to my degree but I won't get to cover it in my course since I've already progressed past that year and the Uni just recently updated their syllabus which only applies to new students.

Accelerated C++. Ignore all other answers as they are inferior.
 

maharg

idspispopd
Yes and yes. It is even, perhaps, more important that you learn from that book as it avoids treating C++ as an extension of C which is a trap a lot of people familiar with C fall into (and become frustrated by). Accelerated C++ is the canonical introduction to the current best practices of C++, and they're a long way off the language's roots.
 

Window

Member
Yes and yes. It is even, perhaps, more important that you learn from that book as it avoids treating C++ as an extension of C which is a trap a lot of people familiar with C fall into (and become frustrated by). Accelerated C++ is the canonical introduction to the current best practices of C++, and they're a long way off the language's roots.

I see. Thanks for that.
 

Ydahs

Member
I think I broke C.

For some reason, if I uncomment either one of four unused variables at the beginning of my main method, my programs dies. I can rename them, I can change their values, but removing them causes chaos.

THIS MAKES NO SENSE
 
I think I broke C.

For some reason, if I uncomment either one of four unused variables at the beginning of my main method, my programs dies. I can rename them, I can change their values, but removing them causes chaos.

THIS MAKES NO SENSE

Sounds like your program is writing into memory it shouldn't and uncommenting those variables exacerbated the issue.
Code is necessary for me to verify.
 

Ydahs

Member
I was just going to send my lecturer a message but it won't hurt to know why it's happening.

I'll send the code via PM. Can't post it here since it's a University assignment.
 

usea

Member
I was just going to send my lecturer a message but it won't hurt to know why it's happening.

I'll send the code via PM. Can't post it here since it's a University assignment.
o_O Lots of people post their university assignments here.

PM it to me too. Not that I will be able to help, but because I'm curious.
 

Ydahs

Member
Actually, problem solved!

"Sounds like your program is writing into memory it shouldn't and uncommenting those variables exacerbated the issue."

Spot on. Your comment made me look further done and it turns out there was an uninitialised integer being passed into an accept call for a socket, which led to a bunch of crazy things occurring.

Thanks. Know I feel really stupid for wasting two hours of my life over something so small...

o_O Lots of people post their university assignments here.

PM it to me too. Not that I will be able to help, but because I'm curious.
Our University has a very strict plagiarism policy. Don't want to risk it!
 

The Technomancer

card-carrying scientician
Hm, I can't figure out why this code isn't working/compiling:
Code:
void Populate(string, vector<string>);

int _tmain(int argc, _TCHAR* argv[])
{
	//population step
	vector<string> Noun;
	Populate("Noun.txt", Noun);

        //stuff

}

void Populate(string Filename, vector<string> &Vector){
	ifstream inFile;
	string BufferString;
	inFile.open(Filename);
	if(!inFile.is_open()){
		cout << "Error: " << Filename << " was not found" << endl;
	}
	while(inFile.good()){
		inFile >> BufferString;
		Vector.push_back(BufferString);
	}
}

Visual Studio says that "more then one instance of the overloaded function Populate matches the argument list".

Any ideas?
 

Spoo

Member
Hm, I can't figure out why this code isn't working/compiling:
Code:
void Populate(string, vector<string>);

int _tmain(int argc, _TCHAR* argv[])
{
	//population step
	vector<string> Noun;
	Populate("Noun.txt", Noun);

        //stuff

}

void Populate(string Filename, vector<string> &Vector){
	ifstream inFile;
	string BufferString;
	inFile.open(Filename);
	if(!inFile.is_open()){
		cout << "Error: " << Filename << " was not found" << endl;
	}
	while(inFile.good()){
		inFile >> BufferString;
		Vector.push_back(BufferString);
	}
}

Visual Studio says that "more then one instance of the overloaded function Populate matches the argument list".

Any ideas?

Your signature doesn't take a reference but your function implementation does.

Change the top line to read: void Populate(string, vector<string>&);
 

SolKane

Member
Got a question here that I'm stuck on. I have to create an array of structures within a class and then initialize them. As I understand it you cannot initialize something within a class definition outside of a structure. But I'm having problems with the syntax. Here's what I've got:


Code:
Struct Foo
{
     string s;
     int i;
     double d;

     Foo (string a, int b, double c)
     { 
          s = a;
          i = b;
          d = c;
      }
}

Class Bar
{ 
  public:  
      Foo array[5];
}

int main ()
{
    Bar object;
    object.array =   { Foo("One", 1, 1.0),
                              Foo("Two", 2, 2.0)
                              Foo("Three", 3, 3.0)
                               Foo("Four", 4, 4.0)
                               Foo("Five", 5, 5.0);
}

Is this correct?
 

Slavik81

Member
No. Bar needs a constructor that does that initialization in its initializer list.

EDIT: Actually, that's not possible either, since Foo is non-POD. You may have to remove its constructor and use aggregate initialization on it too. This is part of why raw arrays are a pain.
 
Got a question here that I'm stuck on. I have to create an array of structures within a class and then initialize them. As I understand it you cannot initialize something within a class definition outside of a structure. But I'm having problems with the syntax. Here's what I've got:


Code:
Struct Foo
{
     string s;
     int i;
     double d;
}

Class Bar
{ 
  public:  
      Foo array[5];
}

int main ()
{
    Bar object;
    object.array =   { { "One", 1, 1.0} ,
                              { "Two", 2, 2.0 } ....;
}

Is this correct?

Try that. Also change string to const char * if that does t work
 

Slavik81

Member
If you really do want to use aggregate initialization and raw arrays (which are usually more trouble than they're worth... just use std::vector and constructors), definitely give a read through this FAQ on the requirements of aggregate and POD types: http://stackoverflow.com/q/4178175/331041

It doesn't mention too much about aggregate initialization, but it probably is sufficient to say that aggregate initialization can be performed for aggregate types on construction. And only on construction, not on assignment.
 
How would one port a code in C++ from Microsoft Visual Studio 2010 to Apple XCode 4?

Depending on the program, the answer is "with great difficulty".

You're not just porting from one compiler to another, but from one platform to another. Sometimes this is simple, for example if it doesn't use any Windows specific APIs and only uses CRT library, but other times it can be extremely complicated.

I'm not sure if there's a better answer to such a broad question
 

wolfmat

Confirmed Asshole
How would one port a code in C++ from Microsoft Visual Studio 2010 to Apple XCode 4?

You make a new project file in XCode, you copy all the source files and assets in, you set compiler options, you treat all errors, you treat all quirks. It usually takes a while, all things considered. Lots of "why is this an error?" -> Google -> Fix. Tenfold that if you have a GUI-heavy application, or one that interfaces with Microsoft products.
 

wolfmat

Confirmed Asshole
Oh yeah, sometimes, it's better to recode from scratch. So really consider that option. If it's less than 10K lines, I don't see why you wouldn't do it.
 

Slavik81

Member
It's not very hard to make a cross-platform application if you design for it up-front. Using a cross-platform framework like Qt, it's pretty straight-forward. Though, bolting it on after the fact can potentially be pretty difficult.
 
Status
Not open for further replies.
Top Bottom