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

luoapp

Member
Any idea how to link to Visual C++ 10 runtime libraries? So I am writing some program requiring linking Fortran and CUDA C++ codes. They all compiled fine, but give me some linking error like those:
sub1.cu.obj:(.text[___isnan]+0x15): undefined reference to `__allshl'
sub1.cu.obj:(.text[_lround]+0x15): undefined reference to `__ftol2_sse'
sub1.cu.obj:(.text[_llround]+0x15): undefined reference to `__ftol2'
sub1.cu.obj:(.text[_lgamma]+0x67b): undefined reference to `__ftol2'

Search online shows those are VC runtime libraries, but I couldn't find out (1) which lib files are runtime libs? (2) where are they? And if anyone has Fortran, C, CUDA mixed programming experience, please do share. Thanks.
 

SolKane

Member
So I am taking a basic C++ class as my first programming foray so forgive me if this is a little too simple :)

I need to write a program that asks the user to input two integers. Store the integers in two separate variables and using the conditional operator determine which integer is the smaller of the two. With what I have so far I can input two variable but for some reason it seems to only be using the first digit of the two numbers inputted. Why is that?

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s1, s2;
	cout << "Please input two numbers" << endl;
	cin >> s1;
	cin >> s2;

	cout << endl;
	
	if(s1 > s2)
		cout << s1 << " is the larger number" << endl;
	else if(s2 > s1)
	    cout << s2 << " is the larger number" << endl;
	
return 0;
}

This has already been addressed but you want to use an int data type rather than a string. Also, your "else if" statement is overly complicated, because it will be problematic if int1 == int2. Instead you could just write:

Code:
        if(s1 > s2)
		cout << s1 << " is the larger number" << endl;
	else
	        cout << s2 << " is the larger number" << endl;
 
I have to say, I've fallen in love with Qt Creator. They've really turned it into a nice IDE. The only things that still keep me stuck on Visual Studio are VAX and some custom plug-ins.



You probably want to snag an IDE as well.

On Windows, Visual Studio Express is solid. Cross-platform, there's Code::Blocks, Eclipse, and (if you're working with Qt) Qt Creator.

If you're on Windows and you don't go with Visual Studio, you'll probably need MinGW. It may or may not be installed along with those IDEs.

So If I'm reading this correctly, visual c++ express also comes with an IDE built in?


Edit: Also, does it shut down and stop working after 30 days, or can I use it for however long?
 

Slavik81

Member
So If I'm reading this correctly, visual c++ express also comes with an IDE built in?

Edit: Also, does it shut down and stop working after 30 days, or can I use it for however long?
Yes, you get an IDE in the package.

The express version works forever. It is not a demo. The main thing the paid version gets you access to is plugins (some of which are fantastic, such as VisualAssistX).
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Nope, although I didn't know C++ had and/or.
 

Bruiserk

Member
No idea if the OP is using some kind of bizarre language extension, but C++ definitely does not support the words "and" and "or".

Why does this seem to work then?

Code:
int main() {
  int a = 4;
  int b = 6;
  if(a == 4 or b == 4) {
    cout <<"Or is compatible";
  } else {
    cout << "Or is not compatible";
  }
}

am I missing something here?
 

fenners

Member
Why does this seem to work then?

Code:
int main() {
  int a = 4;
  int b = 6;
  if(a == 4 or b == 4) {
    cout <<"Or is compatible";
  } else {
    cout << "Or is not compatible";
  }
}

am I missing something here?

What compiler/IDE are you using? That's definitely /not/ standard C/C++/
 
Actually, C90 added the aliases for the logical operators. C++98 and above implement the same standard with regards to logical operator aliases.

Visual Studio doent appear to support it, im curious what compilers do. Although i still may look at the standard later to verify this (its obviously just trivia, but now im curious)
 
Visual Studio doent appear to support it, im curious what compilers do. Although i still may look at the standard later to verify this (its obviously just trivia, but now im curious)


It is indeed part of the original standard. Visual Studio still doesn't entirely conform to the standard (then again even G++ doesn't conform to the entire standard though it supports the alternative form). Microsoft's problem I believe is they don't want to break existing code by including those alias keywords as a compiler default though I do believe you can force the compiler to accept the keywords without using the iso646.h header file by passing in some flag.
 

usea

Member
Depending on which version of the standard you look at, it's under 2.5 or 2.6, the section named "Alternative tokens."

Here's a paste from n3035.pdf (working draft of the new standard). The section is the same in the older version.

2.6 Alternative tokens [lex.digraph]
1 Alternative token representations are provided for some operators and punctuators.
2 In all respects of the language, each alternative token behaves the same, respectively, as its primary token,
except for its spelling. The set of alternative tokens is defined in Table 2.

Code:
Table 2 &#8212; Alternative tokens
Alternative	Primary
<%		{
and		&&
and_eq		&=
%>		}
bitor		|
or_eq		|=
<:		[
or		||
xor_eq		&#710;=
:>		]
xor		&#710;
not		!
%:		#
compl		~
not_eq		!=
%:%:		##
bitand		&
I edited the table so it would look better as a forum post
 

Bruiserk

Member
It is indeed part of the original standard. Visual Studio still doesn't entirely conform to the standard (then again even G++ doesn't conform to the entire standard though it supports the alternative form). Microsoft's problem I believe is they don't want to break existing code by including those alias keywords as a compiler default though I do believe you can force the compiler to accept the keywords without using the iso646.h header file by passing in some flag.

Interesting. I'm glad I brought it up, it was something that was confusing me. Thanks everyone for the help.
 

hitsugi

Member
All right, so I've been working out a problem for my intermediate C++ class (assignment link here for reference), and while everything works (input validation, adds things up correctly, etc.) I have managed to hodge-podge my code to the point where I'm getting this error: "warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data" on lines 46 and 58.

What's worse is, if I touch anything from this point or change doubles back to int, things just get worse and I get errors of "ambiguous call to overloaded function" in main for getHours and getMinutes. Code to follow:

edit - removed horribly ghetto code out of sheer embarrassment, thanks fenners and tokkun.

Any help would be much appreciated :D nudge in the right direction, indication that the above-code is total garbage.. whatever it takes at this point. Thanks!
 

fenners

Member
A few things straight off -

1, you're mixing types - like getHours expects a double for the hour param, but it's declared as an int in the main function. That's why you get the double/int warning.

2, getHours etc don't /do/ anything as far as I can tell from a quick glance, because the params to the function aren't being passed by reference etc... So you'll get nothing out of them. You don't initialize the hours/minutes/addedMins etc variables, so you'll get junk.

[added]
Just saw the muliple definitons of getHours & getMinutes taking different param types... Why? Why do you need to write it twice with the only difference being int/double as param type? The double ones, as I mentioned, wont' pass out their result...
 

tokkun

Member
Comment out the versions of getHours and getMinutes that take doubles. They are full of bugs and don't appear to be necessary for your program.
 

hitsugi

Member
oh my GOD.

I had two versions of this up and I guess at some point I must have pasted that in there (when it had int values) and then began screwing with it because I didn't notice what I had done.

...wow. thanks guys.
 
Hey guys, this is pretty noobert of me, but I'm trying to teach myself C++ and I'm going through how to write and use different functions with parameters and arguments and well...


Code:
//func the system
#include <iostream>
#include <string>

using namespace std;

int addOp (int a, int b);
int subOp (int a, int b);
int divOp (int a, int b);
int MulOp (int a, int b);


int main ()
{
    cout << "Welcome to the Ghetto Calculator\n\n";
    cout << "Select the operation and input two values\n";
    cout << "I will calculate your request and return you a solution.\n\n";

    int x;
    int y;
    string operation;
    int solved;

    cout << "Value 1: " << endl;
    cin >> x;

    cout << "Value 2: " << endl;
    cin >> y;

    cout << "Please specify: (add, sub, mult, div)";
    cin >> operation;

    if (operation == "add")
    {
        solved = addOp(x,y);
        cout << solved;
    }

    else if (operation == "sub")
    {
        solved == subOp(x,y);
        cout << solved;
    }

    else if (operation == "mult")
    {
        solved == MulOp(x,y);
        cout << solved;
    }
    else if (operation == "div")
    {
        solved == divOp(x,y);
        cout << solved;
    }

    else
    {
        cout << "Invalid operation";
    }




  return 0;
}

int addOp(int a, int b)
{
    int answer;
    answer = a+b;
    return answer;
}

int subOp(int a, int b)
{
    int answer;
    answer = a-b;
    return answer;
}

int MulOp(int a, int b)
{
    int answer;
    answer = a*b;
    return answer;
}

int divOp (int a, int b)
{
    int answer;
    answer = a/b;
    return answer;
}

can anyone tell me what I'm doing wrong here? I know its not the most elegant way to do this, but like I said, I'm just trying to learn parameters and functions. Thanks!
 
Code:
    if (operation == "add")
    {
        solved = addOp(x,y);
        cout << solved;
    }

    else if (operation == "sub")
    {
        solved == subOp(x,y);
        cout << solved;
    }

    else if (operation == "mult")
    {
        solved == MulOp(x,y);
        cout << solved;
    }
    else if (operation == "div")
    {
        solved == divOp(x,y);
        cout << solved;
    }

You can get rid of the solved == function stuff. You can just call the function.

Code:
if (operation == 'add')
addOp(x,y)
else if....[etc.]

You're trying to set a variable to equal a function. Just call it and let it do the work in the function and output in the same function.

edit:

Now I have a general query. Whilst still learning the general stuff, one of my professors suggested creating a 'game' like rock paper scissors, so I figured it would be a good idea. I've been thinking about it, and was wondering, if I set it up so that if the computer 'recognised' that the user was using let's say a 'rock' most often, and had it adjust to use whatever beat rock, would that be an extremely rudimentary AI system? Or am I just pulling stings behind the scenes?
 

wolfmat

Confirmed Asshole
can anyone tell me what I'm doing wrong here? I know its not the most elegant way to do this, but like I said, I'm just trying to learn parameters and functions. Thanks!

You wrote
Code:
solved == subOp(x,y);
and
Code:
solved == MulOp(x,y);
and
Code:
solved == divOp(x,y);

But you wanted to write
Code:
solved = subOp(x,y);
and
Code:
solved = MulOp(x,y);
and
Code:
solved = divOp(x,y);

== is for comparison, = is for assignment of values.

You should have consistent uppercase vs lowercase for functions.
 

wolfmat

Confirmed Asshole
Now I have a general query. Whilst still learning the general stuff, one of my professors suggested creating a 'game' like rock paper scissors, so I figured it would be a good idea. I've been thinking about it, and was wondering, if I set it up so that if the computer 'recognised' that the user was using let's say a 'rock' most often, and had it adjust to use whatever beat rock, would that be an extremely rudimentary AI system? Or am I just pulling stings behind the scenes?

You would compute trivial probability and write if .. else clauses according to results. That's just math.

Having said that, it's not easy to say where "pulling strings" ends and AI begins.

Going with the textbook definition, everything is AI as long as input is processed with reference to state to produce output and altered state (including anything to do with games). You have an agent (the program code and its internal state). You have an environment (the input and the referenced state). You have defined success and failure states. You write code that leads to results matching either the success or the failure state. You bias picking for determining results in some way (in this case, look at a state collection to compute probability). Output is mostly a byproduct.

AI is a weird category when it comes to categorizing.
 

usea

Member
Even having the CPU simply choosing rock every time is AI; it's just a bad one.

A system that simply chose what the opponent picked the previous round would also be AI, and a better one.
 

DTKT

Member
Anyone has any good books for intro to C++?

I had one class of intro to Pascal and Pascal OOP and that's pretty much it. I did some java + Javascript on my own but nothing significant.
 
I cannot figure out why when using this switch statement and selecting an option to a function, the function just keeps looping infinitely.

Code:
        int menuChoice;
	bool done = false;
	cin >> menuChoice;
	
	while (!done)
	{

		switch (menuChoice)
		{
		case 1: 
			runGame();
			break;
		case 2: 
			viewScores();
			break;
		case 3:
			deleteScores();
			break;
		case 4: 
			cout <<"Goodbye"<<endl;
			done = true;
			break;
		default: 
			cout << "Not a valid choice.";
			break;
		}
	}
}
void runGame()
{
	cout <<"runGame called" <<endl;
}
void viewScores()
{
	cout << "viewScores called" <<endl;
}
void deleteScores()
{
	cout << "deleteScores called" <<endl;
}

It's frustrating. There has to be something simple I'm overlooking...
 

Chris R

Member
You only set the value of menuChoice once. If you did anything other than 4 the loop would just continue forever, because the value of menuChoice isn't changing.
 
Oh derp. I knew it was something simple.

edit: I seem to be forgetting some switch related stuff.. How can I implement it so that if someone selects other than 1-4, for it to give an error and kick back to the menu options?
 

KorrZ

Member
Anyone has any good books for intro to C++?

I had one class of intro to Pascal and Pascal OOP and that's pretty much it. I did some java + Javascript on my own but nothing significant.

C++ Primer Plus 6th Edition

Probably your best bet. I've been teaching myself C++ from absolutely zero programming experience and its been fantastic. Tons of example programs, explains things thoroughly and breaks down the example code step by step to make sure you understand everything.
 

KorrZ

Member
Oh derp. I knew it was something simple.

edit: I seem to be forgetting some switch related stuff.. How can I implement it so that if someone selects other than 1-4, for it to give an error and kick back to the menu options?

Remove the break from the default case and put your cin inside the loop so it re prompts for input
 

jokkir

Member
Does anyone know how to find the length of a multi dimensional array? The multi dimensional array is:

Code:
char data[SIZE][61] = {
"go;north;south;east;west;start;left;right;home",
"look",
"pick up;gold;platinum;crystal;magic sword",
"drop;gold;platinum;crystal;magic sword",
"attack;crystal;magic sword"
};

I want to know the length of the first instance of the multi-dimensional array
Code:
"go;north;south;east;west;start;left;right;home"

So I can extract each word separated by the semi-colon. Or would I have to go do that in a loop until it reaches the NULL byte?
 
Does anyone know how to find the length of a multi dimensional array? The multi dimensional array is:

Code:
char data[SIZE][61] = {
"go;north;south;east;west;start;left;right;home",
"look",
"pick up;gold;platinum;crystal;magic sword",
"drop;gold;platinum;crystal;magic sword",
"attack;crystal;magic sword"
};

I want to know the length of the first instance of the multi-dimensional array
Code:
"go;north;south;east;west;start;left;right;home"

So I can extract each word separated by the semi-colon. Or would I have to go do that in a loop until it reaches the NULL byte?

strlen(data[0])
 
Alright so I've been toying around with this simple rock paper scissors game, and have all the logic set up, the scores save into a stack 9for learning purposes right now, will change to other type soon) and it all runs perfectly. Now the one thing I'm trying to do is get it to create a single Save_File.txt, in which it can read it, add it to the score from the current operation, and overwrite the old record with the new one each time the program is run. Problem is, I can't even begin to figure out how to go about this?

So I store it as Old Wins: ## Old Losses: ## Old Ties: ## > program runs and reads the past records > program runs and outputs the record this time > program adds the New Wins to Old Wins, New Losses to Old Losses, New Ties to Old Ties.

I'm thinking if I read the file at the start and place those into an entirely different stack, run the program and have the new stack, then set each value as Old + New? I hope that makes sense how I worded it.
 

Arsenic

Member
Thanks to whoever reads this:

So in my intro level C++ course I have this program I had to code that checks for high/low temperatures and its averages, total rainfall and its averages for the year, through user inputted data. Everything is sent to/from a structure.

I get an error:
"cannot convert 'double' to 'double*' for argument '1' to 'double findLowestTemp(double*, int)."

I get the same error for the findHighestTemp functions.

I'm supposed to be able to pass an entire array through the function, and return one answer. I'm thinking it's works differently with structures involved but I can't find anything good in my textbook to help me understand.

Here are the codes that I know are trouble:

Prototypes:
Code:
double findLowestTemp  (double[], int);
double findHighestTemp (double[], int);

The calls:
Code:
lowestTemp = findLowestTemp (month[numMonths].lowTemp, numMonths);
highestTemp = findHighestTemp (month[numMonths].highTemp, numMonths);

and the function headers:
Code:
double findLowestTemp(double lowTemp[], int months)
double findHighestTemp(double highTemp[], int months)


And the full program. Don't make fun of it's crappiness :(
Code:
#include <iostream>
using namespace std;

struct Mweather
{
	double totalRain,
	       highTemp,
	       lowTemp,
	       avgTemp;
};

double computeAvgTemp  (double, double);
Mweather findLowestTemp  (double[], int);
Mweather findHighestTemp (double[], int);

int main()
{

    const int numMonths=3;
    int       yearlyRain=0;
    double    avgYearlyRain=0, highestTemp=0, lowestTemp=0;
	Mweather  month[numMonths];

    for (int count=0;count<numMonths;count++){
		cout << "--For the " << count+1;
            if (count == 0)
                cout << "st ";
            else if (count == 1)
                cout << "nd ";
            else if (count == 2)
                cout << "rd ";
            else
                cout << "th ";
        cout << "month--" << endl;
        cout << "Total rainfall: ";
        cin  >> month[count].totalRain;
        cout << "Highest temperature: ";
        cin  >> month[count].highTemp;
        cout << "Lowest temperature: ";
		cin  >> month[count].lowTemp;
		cout << endl << endl;
    }

    for (int count=0; count < numMonths; count++){
        month[count].avgTemp = computeAvgTemp(month[count].highTemp, month[count].lowTemp);
        cout << "The average temperature for month " << count+1 << " is: "
             << month[count].avgTemp << "." << endl;
    }

    for (int count=0; count < numMonths; count++)
            yearlyRain += month[count].totalRain;

        avgYearlyRain = yearlyRain / numMonths;

        cout << "\nThe average rainfall for the year is " << avgYearlyRain << ".";
        cout << "\nThe total rainfail for the year is " << yearlyRain << ".";

    lowestTemp = findLowestTemp (month[numMonths].lowTemp, numMonths);
        cout << "The lowest temperature for the year was " << lowestTemp
             << " degrees.";
    highestTemp = findHighestTemp (month[numMonths].highTemp, numMonths);
        cout << "The highest temperature for the year was " << highestTemp
             << " degrees.";

    return 0;

}

    double computeAvgTemp(double highest, double lowest)
    {
        double average, twoTemps;

        for (int count=0; count < 3; count++){
            twoTemps = highest + lowest;
            average = twoTemps / 2;
        }

         return average;
    }

    double findLowestTemp(double lowTemp[], int months)
    {
        double lowestTemp=360;        //assigned high value

        for(int count=0; count < months; count++){

            if (lowTemp[count] > lowestTemp)  
                lowestTemp = lowTemp[count]; 

            count++;
        }

        return lowestTemp;

    }

    double findHighestTemp(double highTemp[], int months)
    {
        double highestTemp=0;       

        for(int count=0; count < months; count++){

            if (highTemp[count] < highestTemp) 
                highestTemp = highTemp[count]; 

            count++;
        }

        return highestTemp;

    }

Thanks again!
 

Cindres

Vied for a tag related to cocks, so here it is.
Thanks to whoever reads this:

So in my intro level C++ course I have this program I had to code that checks for high/low temperatures and its averages, total rainfall and its averages for the year, through user inputted data. Everything is sent to/from a structure.

I get an error:
"cannot convert 'double' to 'double*' for argument '1' to 'double findLowestTemp(double*, int)."

I get the same error for the findHighestTemp functions.

I'm supposed to be able to pass an entire array through the function, and return one answer. I'm thinking it's works differently with structures involved but I can't find anything good in my textbook to help me understand.

Here are the codes that I know are trouble:

Prototypes:

The calls:

and the function headers:


And the full program. Don't make fun of it's crappiness :(

Thanks again!

EDIT: Was just about to post that I was getting an error too then I fixed it so give me a second while i edit this post to give you the solution!

EDIT 2:

Right then, so the issue you're having is that you're trying to pass a single double value (month[numMonths].lowTemp) into the functions findLowestTemp and findHighestTemp, when the parameter is asking for an array of doubles (double lowTemp[]).

What you'll want to do is pass in your "months" variable, which as far as I can tell is an array of Mweather, size 3.
Firstly, change
Code:
lowestTemp = findLowestTemp (month[numMonths].lowTemp, numMonths);
highestTemp = findHighestTemp (month[numMonths].highTemp, numMonths);

to

Code:
lowestTemp = findLowestTemp (month, numMonths);
highestTemp = findHighestTemp (month, numMonths);

And what we're going to do is let the functions pick out the highTemp and lowTemp variables.
Now my error here was it was still saying we were trying to convert months[3] to a double [], head to the top of the code and change

Code:
Mweather findLowestTemp  (double[], int);
Mweather findHighestTemp (double[], int);

to

Code:
[B]double[/B] findLowestTemp  ([B]Mweather[][/B], int);
[B]double[/B] findHighestTemp ([B]Mweather[][/B], int);
(Changes bolded).

Then in the functions for finding the lowest and highest you'll wnat to make it pick out the lowtemp and hightemp variables as it goes on.
Code:
   double findLowestTemp(double lowTemp[], int months)
    {
        double lowestTemp=360;        //assigned high value

        for(int count=0; count < months; count++){

            if (lowTemp[count] > lowestTemp)  
                lowestTemp = lowTemp[count]; 

            count++;
        }

        return lowestTemp;

    }

Change this to match this:
Code:
double findLowestTemp([B]Mweather lowTemp[][/B], int months)
    {
        double lowestTemp=360;        //assigned high value

        for(int count=0; count < months; count++){

            if (l[B]owTemp[count].lowTemp[/B] > lowestTemp)  
                lowestTemp = [B]lowTemp[count].lowTemp[/B];
        }

        return lowestTemp;

    }

So it's now accepting an array of Mweather, and in the if statement it picks up the lowTemp value. Do the same for the findHighestTemp function and you should be able to compile as I was.

Did spot some other errors in the code which is why I haven't actually attempted to test the code with input once it ran because I'll let you find those ;)

However, one thing I will note is that you've used count++; inside the for loops in those two functions, this isn't necessary as count++ in the for constructor does that for you as it loops around.

Hopefully I got this right, it compiles for me anyway without errors, fairly new to C++ myself but i'm profficient in Java and these are mostly syntax errors anyway.

EDIT 3: Ran through the code and it works, but there are issues in your findHighestTemp and findLowestTemp functions that will give you the wrong values at the end, I'll let you figure those out for yourself ;)

Here's my full code WITHOUT that last thing I just mentioned changed incase anything doesn't work that you change:
Code:
#include <iostream>
using namespace std;

struct Mweather
{
	double totalRain,
	       highTemp,
	       lowTemp,
	       avgTemp;
};

double computeAvgTemp  (double, double);
double findLowestTemp  (Mweather[], int);
double findHighestTemp (Mweather[], int);

int main()
{

    const int numMonths=3;
    int       yearlyRain=0;
    double    avgYearlyRain=0, highestTemp=0, lowestTemp=0;
	Mweather  month[numMonths];

    for (int count=0;count<numMonths;count++){
		cout << "--For the " << count+1;
            if (count == 0)
                cout << "st ";
            else if (count == 1)
                cout << "nd ";
            else if (count == 2)
                cout << "rd ";
            else
                cout << "th ";
        cout << "month--" << endl;
        cout << "Total rainfall: ";
        cin  >> month[count].totalRain;
        cout << "Highest temperature: ";
        cin  >> month[count].highTemp;
        cout << "Lowest temperature: ";
		cin  >> month[count].lowTemp;
		cout << endl << endl;
    }

    for (int count=0; count < numMonths; count++){
        month[count].avgTemp = computeAvgTemp(month[count].highTemp, month[count].lowTemp);
        cout << "The average temperature for month " << count+1 << " is: "
             << month[count].avgTemp << "." << endl;
    }

    for (int count=0; count < numMonths; count++)
            yearlyRain += month[count].totalRain;

        avgYearlyRain = yearlyRain / numMonths;

        cout << "\nThe average rainfall for the year is " << avgYearlyRain << ".";
        cout << "\nThe total rainfail for the year is " << yearlyRain << ".";

    lowestTemp = findLowestTemp (month, numMonths);
        cout << "The lowest temperature for the year was " << lowestTemp
             << " degrees.";
    highestTemp = findHighestTemp (month, numMonths);
        cout << "The highest temperature for the year was " << highestTemp
             << " degrees.";

    return 0;

}

    double computeAvgTemp(double highest, double lowest)
    {
        double average, twoTemps;

        for (int count=0; count < 3; count++){
            twoTemps = highest + lowest;
            average = twoTemps / 2;
        }

         return average;
    }

    double findLowestTemp(Mweather lowTemp[], int months)
    {
        double lowestTemp=360;        //assigned high value
		
        for(int count=0; count < months; count++){

            if (lowTemp[count].lowTemp > lowestTemp)  
                lowestTemp = lowTemp[count].lowTemp;
        }

        return lowestTemp;

    }

    double findHighestTemp(Mweather highTemp[], int months)
    {
        double highestTemp=0;       

        for(int count=0; count < months; count++){

            if (highTemp[count].highTemp < highestTemp) 
                highestTemp = highTemp[count].highTemp; 

            count++;
        }

        return highestTemp;

    }
 

Arsenic

Member

You are amazing. Thanks a lot for taking the time to explain, I really understand what I did wrong now.

I figured out the other mistakes quickly (had to reverse the > and < signs) and I've noticed a few more. Getting the program to compile surely helps to find the logical errors. I appreciate the help!

I'll work on the rest tomorrow and refine the code a bit, and post so you can see where it headed. I'm pretty sure i can just use one function to find both the highest and lowest temps (must pass a variable through reference though). I'm rusty with the functions but I'll come back to me eventually.
 

Cindres

Vied for a tag related to cocks, so here it is.
You are amazing. Thanks a lot for taking the time to explain, I really understand what I did wrong now.

I figured out the other mistakes quickly (had to reverse the > and < signs) and I've noticed a few more. Getting the program to compile surely helps to find the logical errors. I appreciate the help!

I'll work on the rest tomorrow and refine the code a bit, and post so you can see where it headed. I'm pretty sure i can just use one function to find both the highest and lowest temps (must pass a variable through reference though). I'm rusty with the functions but I'll come back to me eventually.

Awesome, glad to help. May have an interview coming up soon that may ask about C++ in the interview so I'm gonna be checking this thread a lot to get used to finding/fixing problems in C++ :p
 

Bruiserk

Member
edit: nevermind. I figured out the answer. I'll leave the question up for curiosity sake.

This is the question:

Write a program that reads in words from cin (ending with EOF, i.e. ctrl-d, as usual) and then prints the word that occurs most frequently (and also print its frequency count). If more than one word ties for the most frequent, then print each of those words in alphabetical order.

I am getting a segmentation error with this code:

http://pastebin.com/11FmMpSv

Code:
int main() {
  cout << "Enter some words: ";
  vector<string> words;
  string w;
  while(cin >> w) {
    words.push_back(w);
  }
  sort(words.begin(), words.end());
  int count = 1;
  int most_so_far = 0;
  vector<string> most_frequent;
  for(int i = 0; i < words.size(); ++i) {
    if(words[i] == words[i+1]) {
      ++count;
    }
    else if(words[i] != words[i+1]) {
      if(count > most_so_far) {
	most_so_far = count;
	most_frequent.clear();
	most_frequent.push_back(words[i]);
	count = 1;
      }
      else if(count == most_so_far) {
	most_frequent.push_back(words[i]);
	count = 1;
      }
      else {        //count < most_so_far
	count = 1;
      }
    }
  }
  sort(most_frequent.begin(), most_frequent.end());
  
  cout << "The most frequently occuring words are: \n\n";
  
  for(int i = 0; i < most_frequent.size(); ++i) {
    cout << most_so_far << " " << most_frequent[i] << endl;
  }
  
}

Any advice?
 
Status
Not open for further replies.
Top Bottom