Hi, so I'm having problems finding the longest word in a given input. This code doesn't work, and I'm pretty stuck ; ; I want to include the size(); or length(); operations, but I'm having trouble. What am I doing wrong and what am I missing? Please HELP!
// includes
#include <iostream>
#include <string>
#include <vector>
// using statements
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
Hi, so I'm having problems finding the longest word in a given input. This code doesn't work, and I'm pretty stuck ;
Have you used your compiler's debugger?
I want to include the size(); or length(); operations, but I'm having trouble.
You don't randomly throw things together. You must know each and every step of what you're doing.
What am I doing wrong and what am I missing?
First, you should learn to diagnose your own problems by learning to use the debugger. It is a mandatory tool to learn if you want to write any program and diagnose errors.
Code:
if (str_length == str_longest)
So what is the value of str_longest and str_length the first time this statement is executed? It isn't any known value, since you didn't initialize them. They could be 0, 435, -4323, 32432432, who knows. Variables don't magically get their values, you have to set them to something.
Not if he's interested in word length, it shouldn't.
One problem I do see is that you're adding s to the "longest" vector twice in one case. I doubt that's what you want. Otherwise, it's a fairly good approach to the problem once you replace those meaningless variables with the appropriate member functions.
That really isn't an excuse to not know to initialize variables to a value. That should have been covered long before you attempted this assignment.
When learning C++, you must understand everything you've learned up to the point you write the program. If the C++ book you're using discusses variables, how they're assigned, etc. then you must understand everything about that before writing a program using that concept. This means understanding all the example programs given to you before you start writing your own.
You're using vectors, but do not know about assigning variables. Using STL vectors assumes you know the basics of assigning variables.
Your approach is, erm, sub optimal. You don´t need a vector at all, simply store the longest string so far. Furthermore you´re comparing strings lexicographically instead of comparing string lengths:
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.