>The perils of replying before reading page 2
I always set the number of posts per page to the maximum so as to avoid that problem most of the time. :)
>The perils of replying before reading page 2
I always set the number of posts per page to the maximum so as to avoid that problem most of the time. :)
>And why do you think it is sooo stupid
Because it's useless trivia. Questions like this are basically like tricky riddles: unless you already know it, you probably won't figure it out on your own. You also won't use it in the real world. Even the smallest embedded system will have enough spare memory for a temporary variable, and if it doesn't then there are far better ways to optimize space than to restrict the flexibility of your swap. It's also dreadfully easy to "improve" the trick and break everything, as vegaseat proved. Yes, it's good to know the trick, but it's even better to know why it shouldn't be used.
>the creative kind that get inspired by your puzzles, and the "go by the book apparatchiks"
There's a time and a place for creativity. Code should be written with clarity in mind, and ancient tricks that only serve to create bugs and obfuscate things have no place there. Be creative in your algorithms and you'll be a much better programmer for it. Be creative in "cool" micro-optimization code tricks and you'll just be shrugged off as an idiot who has never worked in the real world.
I've already been inspired by these puzzles, I've already solved them, and now I'm inspired by a higher quality of puzzle. You obviously take no pride in your work, or you would try harder to learn the "book" as well as think outside the box, and when to use …
>Sorry, change the "of any type" to "integers only".
How about changing "macro to swap two arguments of any type" to "silly macro to break everything". It's still broken because you're modifying a variable more than once between sequence points. This isn't a difficult rule to figure out, I can't see why so many people have so much trouble with it.
I would word those questions differently in an interview:
>1.Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
Translation: Expain recursion.
>2.Exchange two numbers without using a temporary variable.
Translation: Explain why exchanging two numbers without a temporary variable is the height of stupidity.
>3.Find if the given number is a power of 2.
Translation: Find if the given number is a power of 2. ;) This is actually a useful exercise in bit twiddling and the result can be used in real code.
>4.Multiply x by 7 without using multiplication (*) operator.
Translation: How would you multiply without using the (*) operator, and why would I fire you if you did it in our source base?
Don't forget to read all of my post. Your code has a subtle bug that needs to be fixed.
>Comeau may be a conforming c++ compiler but it contains no C support
Who said anything about C? As far as I can tell, you're the first person to mention anything but C++ in this thread.
>You have to get all that from someplace else
It's a good thing Comeau links you to Dinkumware's excellent standard C and C++ libraries then... :rolleyes:
>And as far as I can tell it is only command-line driven c++ compiler with no IDE
Anyone with half a brain can get Textpad on Windows and link a command line compiler with it. I think kids these days are too reliant on IDE's to solve all of their problems anyway.
>For MS-DOS, the best FREE conforming compiler is Dev-C++ from bloodshed.net.
MS-DOS? Have you gone senile? Dev-C++ is primarily a semi-decent IDE wrapped around GCC and ported for Windows. I have serious doubts that GCC could even run on DOS, much less with anything remotely resembling Dev-C++'s IDE. But yes, GCC is a more than acceptable compiler(s). MS-DOS...ironic that you were talking about *nix programmers working in the ancient past two sentences ago... :rolleyes:
>cin.getline(linebuffer,100);
This should be
file.getline(linebuffer,100);
The program is stopping dead in its tracks because the loop is keyed on whether the file is empty or not, and you never read from the file, just standard input.
Also, using eof() as a loop condition is wrong because the eofbit is only set for the stream after you try and fail to read. This will usually cause the loop to iterate one more time than you expect.
>It's one of the best C++ compilers out there, has the highest ANSI
>compliance of them all (at least for the Win/Tel platform) and excellent performance.
Um, no? Borland 5.5 is nice for an older compiler, but it's far from the most conforming, which is Comeau, and it fails to make the top 5 in compliance.
>I turned off pm because someone started spamming me.
Nobody has ever spammed my private messages. Either I'm liked too much, liked to little, or the flaming I give people when they send me an inappropriate PM is sufficient to quell the desire. ;)
Well, what constitutes a number? How about an operator? Determining if the token is a valid operator is simple, just keep a list of valid operator tokens and compare the string. Numbers are harder unless you restrict yourself to the basic integers where the only valid characters are, for example, the decimal digits '0' through '9'.
And the rest of the error is? Post your entire compiler output when you build the application.
>but trying to code it, it seems so complicated
That's because it is complicated. Sorry.
>Is important to learn them by heart.
That's stupid, and a waste of your brain. It's important to understand them. Beyond that, there's plenty of reference material so that you don't need to spend time memorizing things that can be looked up. Learning the algorithms by heart can come out of understanding them if you use them fairly regularly, but memorizing for the sake of seeming intelligent is dumb.
>this is not the biggest dificulty in the world
Judging from your code, apparently it is.
>Hope it helps
No, as a matter of fact, it doesn't. Your code is non-portable, and very poorly written. If giving the OP a freebie doesn't get him expelled, you'll have taught him bad habits. So no, you've hurt more than helped. Shall we go over the bad parts of your code?
>#include <conio.h>
Not portable, this will only work on Windows compilers that support Borland's conio.h header. Most of the time, conio.h is unnecessary and ignorant people include it so that they can use getch() for no good reason.
>#include <dir.h>
Also not portable. I applaud your desire to check if the file exists properly, but that doesn't mean your solution is what was desired, and it certainly doesn't give you free rights to post any platform or compiler specific code that pops into your head.
>void main(int argc, char **argv)
void main is wrong. It always has been, it always will be. I can't stress enough that if you use void main, you will be tagged as a retard, and nobody who knows anything will trust you.
>if (searchpath(argv[1]))
searchpath() is not portable. In fact, it's not even well known, so this particular solution is very poor on a forum that stresses portable solutions. Even worse, argv[1] is not guaranteed to be meaningful. It may be a null pointer, and I'd …
>Is resize () a function that comes with a specific library?
It's a member function of the string class, which I assumed that you were using because you declared pal and rev as string.
>can I still use a string by itself, or do I have to use a string array to be
>able to read each separate word?
You can do either, though you'll find life to be much simpler if you use an array of strings, one for each word. Otherwise you get into tokenizing and all of that muck. But replacing an integer with it's word representation isn't exactly the simplest of projects if you intend to do it right.
>Or if I have to put different names in order it confuses me if I have to
>use a single string for each name or not?
It's much easier to break the string up into an array (or better, a vector) of separate words if you want to re-order them.
>Can anyone explain me why is the first one wrong
C++ strings grow as needed, but that doesn't mean you can use any index and it'll work. You have to either force the string to grow by using push_back or +=, or resize it explicitly. In other words, this is an empty string. It has no characters, and no room to hold any characters:
string rev;
This is wrong because the string is empty, yet you're trying to use it as if it were not:
rev[N-i-1]=pal[i];
The second problem is that your else keyword has a semicolon after it, which it shouldn't. Compare this with what you wrote:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string pal, rev;
int N;
cout<<"Enter a word to check if it is a palindrome: ";
cin>>pal;
N=pal.length();
rev.resize(pal.length());
for (int i=N-1; i>=0; i--)
{
rev[N-i-1]=pal[i];
}
if (pal==rev )
{
cout<<endl<<pal<<" is a Palindrome";
}
else
{
cout<<endl<<pal<<" is not a palindrome";
}
cout<<endl;
}
>How important is it to learn and understand sorting algorithms and routines?
It's very important. Even if you always use libraries (which is somewhat silly since libraries are designed to be generic and you may need something specific), sorting algorithms cover a huge number of techniques and concepts for designing, implementing, and analyzing algorithms in general. So if you know about sorting, you'll have an easier time with other (seemingly unrelated) algorithms, and even data structures.
Can you be more specific?
>How do you compare a word with itself to check if it is a palindrome?
This is a classic problem, and you already have the tools to solve it. Give it a shot and see what you can come up with.
>when I try to use functions to make a program, i do not know how to use arrays
On the surface, nothing changes. You declare an array as a function parameter the same way. The only difference is that you don't need the size, and it's a good idea to pass the size as a separate parameter:
#include <iostream>
void print_array ( int a[], int size )
{
for ( int i = 0; i < size; i++ )
std::cout<< a[i] <<'\n';
}
int main()
{
int a[] = {1,2,3,4,5};
print_array ( a, 5 );
}
>I am lost on how to find that duplicate!
Rash's suggestion is the simplest (and you should use it for now), but far from the most efficient. Just as a taste of the other options, you can sort the array and then check adjacent values to see if they're the same, or you can use an existence table:
#include <iostream>
template <typename T, int sz>
char (&array(T(&)[sz]))[sz];
void print_duplicates ( int a[], int size )
{
int exist[10] = {0};
for ( int i = 0; i < size; i++ )
++exist[a[i]];
for ( int i = 0; i < sizeof array ( exist ); i++ ) {
if ( exist[i] > 1 )
std::cout<< i <<" is duplicated "
<< exist[i] - 1 <<" times\n";
}
}
int main()
{
int a[] = {5,4,7,6,5,6,7,8,9,3,4,5,6,7,8};
print_duplicates ( a, sizeof array ( a ) );
}
An existence table is an …
An array is just about the simplest and most useful thing you can think of. Imagine a line of boxes numbered 0 to N, where N is some arbitrary number. To put something in the fifth box, you walk over to the one with the number 4 (because they start at 0), and drop the thing in it. Then you walk back to the beginning of the row. To get the thing back, you walk back to the box with 4 and grab the thing.
Let's say that thing is a number, 123. The C++ code to create a line of ten boxes numbered 0 to 9 is:
int box[10];
You can then put the thing in the fifth box like this:
box[4] = 123;
Then to get the thing back, you do the same thing, except with a spare box on the left, which we'll call thing:
int thing = box[4];
If you want every thing in the line of boxes, you go from one end to the other and grab the things in each box:
for ( int i = 0; i < 10; i++ )
std::cout<< box[i] <<'\n';
Or you could go from the other end:
for ( int i = 9; i >= 0; i-- )
std::cout<< box[i] <<'\n';
Just about any use of an array is some variation of the above.
>I know that my VS C++ 6.0
Visual C++ 6 is a very poor compiler for C++.
>automatically sets these arguments when I choose a simple Application
Then you should start with an empty project. Unless you're using command line arguments, there's no need to include those parameters in your definition of main.
>But it would be nice to have a reference to what they do.
Sorry, but the only reference that seems like what you want is the C++ standard. It covers the entire language in painful detail.
>how do i fix that?
It was written for C++. Include <cctype> instead of <ctype.h> and compile as C++. If that doesn't work, get a newer compiler. If that's not an option, just remove the std:: parts until it compiles.
>what if i want to convert the first letter of each word in the string to uppercase?
You convert the first character and the first character after whitespace to upper case:
void first_word ( char *s )
{
bool upper = true;
while ( *s != '\0' ) {
if ( upper && !std::isspace ( (unsigned char)*s ) ) {
*s = std::toupper ( (unsigned char)*s );
upper = false;
}
else if ( !upper && std::isspace ( (unsigned char)*s ) )
upper = true;
*++s;
}
}
>I'm too white and can't dance as well:
It's easy, just shake it, shake it, shake it. Then shake it, shake it, shake it again:
#include <stdio.h>
#include <limits.h>
#define HEXIT ( CHAR_BIT / 2 )
unsigned char swap_nibble ( unsigned char x )
{
return x << HEXIT >> HEXIT << HEXIT >> HEXIT << HEXIT >> HEXIT << HEXIT
| x >> HEXIT << HEXIT >> HEXIT << HEXIT >> HEXIT << HEXIT >> HEXIT;
}
int main ( void )
{
unsigned char x = 0xEA;
printf ( "Before: 0x%X\n", x );
printf ( "After: 0x%X\n", swap_nibble ( x ) );
return 0;
}
>Today we are going to swap the nibbles around in a byte
Pfft, too easy. Do the shuffle: shift left shift right shift left OR shift right:
#include <stdio.h>
#include <limits.h>
#define HEXIT ( CHAR_BIT / 2 )
unsigned char swap_nibble ( unsigned char x )
{
return x << HEXIT >> HEXIT << HEXIT | x >> HEXIT;
}
int main ( void )
{
unsigned char x = 0xEA;
printf ( "Before: 0x%X\n", x );
printf ( "After: 0x%X\n", swap_nibble ( x ) );
return 0;
}
You have quite a few errors. This at least compiles:
namespace Error {
struct Syntax_err {
const char* p;
Syntax_err (const char *q) {p=q;};
};
struct File_err {};
}
namespace Truck_Manager {
using namespace Time;
using namespace Error;
enum Dest { Aachen, Bfeld, Dortm, Duis, Duess, Essen, Kassel, Koeln, Muenstr, WTal };
enum Stat { Jam, Flat_tyre, Accident, Load_Unload, Driving };
Dest rand_Dest() { return (Dest)( rand() % 10 ); }
Stat rand_Stat() { return (Stat)( rand() % 5 ); }
class Truck {
private:
unsigned km_passed;
unsigned km_overall;
Stat curr_stat;
Dest curr_dest;
list<Dest> QDPs; // QDPs == Queued Delivery Places
Time_Sim so_far; // Time driven so far
short occ_capacity; // occupied freight capacity
bool mutable dest_success; // True upon successful destination
public: // Maintenance Functions
Truck (unsigned km_p, unsigned km_all, Time_Sim b, short cap, Dest a=rand_Dest(), Stat c=rand_Stat());
void Print_WI(Truck T, short num) const; // current Working Info
inline void add_dest(Truck T, Dest new_d); // adds a new destination for a truck
void add_stat(Truck T, Stat new_s); // adds event for a given truck
int tmp_save(void); // temp save upon dest_success=1
void update_queue(Truck T, Dest new_curr_dest, bool a);
// Output Functions
inline unsigned get_km_passed(void) const { return km_passed;};
inline unsigned get_km_overall(void) const { return km_overall;};
inline Stat get_stat(void) const {return curr_stat;};
inline Dest get_dest(void) const {return curr_dest;};
//inline void get_tim_e(Time_Sim a) const {Time_Sim::print(Time_Sim a);}; // ?????????
inline short get_capacity(void) const {return occ_capacity;};
};
}
void Truck_Manager::Truck::Print_WI(Truck T, short num) const {
cout << "\n\n\n\n\n" << " Working info …
What errors are you getting? Can you post them as well, please?
You can edit and delete a post within 30 minutes of posting it.
>Take a look on:http://www.daniweb.com/techtalkforums/thread27267.html
Why did you link to a thread where I gave the exact same answer? Dieter's solution was poor (as stated in that thread), so there's no point in (basically) repeating what I said.
Don't forget to account for the first value:
if ( fin >> val )
{
sum += val;
++count;
min = max = val;
while ( fin >> val )
{
if ( val < min )
{
min = val;
}
if ( val > max )
{
max = val;
}
sum += val;
++count;
}
}
On a side note, this is very, very wrong:
count=count++;
It modifies count twice between sequence points, which is undefined.
You're using a Win32 application project when you want a console application project. Win32 applications expect WinMain instead of main.
>here is what i did but it gives average = 77
Um...what's the problem with getting the correct answer?
>fin >> isFirst;
I think you mean:
fin>> val;
isFirst doesn't strike me as a data variable, it seems more like a status variable. You don't even need it. Oddly enough, I didn't bother looking at Dave's code, but my solution is only slightly different (but it avoids undefined behavior in the case of an empty or non-existent file):
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream fin("inFile.txt");
int val;
if (fin >> val) {
int min, max;
min = max = val;
while (fin >> val)
{
if (val < min)
min = val;
if (val > max)
max = val;
}
cout << "Largest value is " << max << ", smallest value is " << min << "\n";
}
return 0;
}
Great minds think alike, I suppose.
>i tried every possible way u suggested me and it still doesnt work.
Then instead of looking at the suggestions and implementing them they way you think they should be done, actually try them as they are written. In my experience, Dave doesn't post untested code.
>*dirs = &strsep(thePath, ':')
Let's look at it like this because it's easier to pick out the errors. dirs is an array of pointer to char. When you subscript dirs, you get a pointer to char, but when you dereference that, you get a single char. So we have this so far as a type map:
char = &strsep(thePath, ':')
Now, since strsep returns a pointer to char, and you take the address of that pointer, you get this:
char = char**
See the problem? All in all, you're thinking too hard, and casting too much:
int parsePath ( char *dirs[] )
{
char *path = getenv ( "PATH" );
char *copy;
char *tok;
int n = 0;
if ( path == NULL )
return 0;
copy = malloc ( strlen ( path ) + 1 );
strcpy ( copy, path );
for ( tok = strtok ( copy, ":" ); tok != NULL; tok = strtok ( NULL, ":" ) ) {
dirs[n] = malloc ( strlen ( tok ) + 1 );
if ( dirs[n] == NULL )
break;
strcpy ( dirs[n++], tok );
}
return n;
}
>Four characters as in s-i-z-e. It's easier to code with shorter names.
Don't use your infernal logic on me! ;)
>length() was left in the string class for backwards compatibility with something
The string class existed in C++ before the STL was adopted, so length() was kept for backward compatibility with existing code and size() added in a poor attempt to make string more like a standard container.
>Also, size is four characters while length is six.
I find that hard to believe, since length() returns size(). Perhaps you're thinking of capacity(), in which case your suggestion is incorrect because the result of capacity() is largely implementation-dependent.
>You don't have to use it, and size_t will always work.
Chapter and verse, please.
>but either way, the size() function is guaranteed to be a constant-time operation.
Um, no. The standard says that size() "should" have constant complexity, not "shall" have constant complexity. That means that you can generally assume that calling size() is constant, but it's not guaranteed.
Enumerations are just convenient sets of named integers. For example, in your code, scalene is 0, isosceles is 1, equilateral is 2, and noTriangle is 3. Printing out one of those low values as a char will likely give you something funky. You can fix it by returning a string instead:
#include <iostream>
using namespace std;
enum triangleType {scalene, isosceles, equilateral, noTriangle};
char *tostr[] = {"scalene", "isosceles", "equilateral", "noTriangle"};
char *triangleShape (int&, int&, int&);
int main()
{
int side1, side2, side3;
char *shape;
cout<<"Please enter the desired length of the sides of the triangle."<<endl;
cin>> side1>>side2>>side3;
shape = triangleShape (side1, side2, side3);
cout<<"The shape of the triangle is: "<<shape<<endl;
return 0;
}
char *triangleShape (int& side1, int& side2, int& side3)
{
char *shape;
if (side1==side2 && side2==side3)
shape = tostr[equilateral];
else if (side1==side2 || side1==side3 || side2==side3)
shape = tostr[isosceles];
else if (side1!=side2 && side1!=side3)
shape = tostr[scalene];
else if (side1+side2<side3 || side1+side3<side2 || side2+side3<side2)
shape = tostr[noTriangle];
return shape;
}
When you get a syntax error, it's customary to post the code as well as the error. :rolleyes:
I would imagine that you initialize encryption with asterisks, right? So let's walk through the execution with that assumption in mind:
for ( int i = 0; i < 5; i++ )
You create i and set it to 0. Since i is less than 5, the body of the loop is executed.
if (encryption[i] == '*' )
Since encryption was filled with asterisks, this test is true as the first character is indeed '*'. The body of the condition is executed:
return i;
0 is returned.
You should also be aware that this is incorrect:
if ( i == 4 )
Since i was declared in the for loop, it only exists until the end of the loop. So any conforming compiler will fail to compile this function because i doesn't exist at this point.
>Q.E.D.
Yes, but is it correct? The question clearly states "variables" yet your cute little trick will only work on integral types. What about pointers? If a and b are pointers and they point to the same object, you certainly won't get a swap out of this.
>it would skip the 0's in the first column
Well that's easy. Leading zeros are meaningless on an integer, so they're ignored. If you want the whole string, read it as a string instead of an integer.
>After this it would replace everything with 0's.
Well, your array is of size 100 and there are only 30 records in the file you gave us...
>It is skipping some of the datas.
Which parts of the data are being skipped? Help us to help you by narrowing down the problem as much as possible. Otherwise we'll just ignore you.
>Another way to purge all those wobbly '\n' ...
That example is incompete, which is why cin.ignore is a superior alternative. It forces you to provide all of the requisite information whereas with the loop approach it's easy to miss a very important test for end-of-file. The correct loop would be:
while (std::cin.get(ch) && ch != '\n')
;
Or using the C-style alternative:
while ((ch = std::cin.get()) != EOF && ch != '\n')
;
>What would you use to enter text into an array (such as a name)?
cin.getline, of course. You're missing the point and focusing on your strings while the problem is here:
cin>>your_student.grade_1cr[i];
Add this, since you seem incapable of solving a problem after being told what it is:
cin>>your_student.grade_1cr[i];
cin.ignore(numeric_limits<streamsize>::max(), '\n');
And don't forget to include <limits>.
>the cin.getline is mentioned in two C++ books I have as a way to enter in a string (where you can't with just "cin".
You can enter a string with cin's operator>>, just not one with whitespace by default. And that has no bearing on the problem at hand. You use cin.getline to read a string, then you use cin>> to read a number. That leaves a newline in the stream and the next call to cin.getline appears to be skipped because it immediately sees the termination character.
>Also, what do you mean by "code tags"?
Code tags. Use them when posting code.
It's hardly a strange problem since everybody sees it when learning C or C++. getline reads characters until a newline character is encountered, but cin>> leaves newlines on the stream. So a cin>> followed by a getline will typically cause problems.
>As always, I appreciate your help
Apparently not enough to use code tags.
>i am a member.
I don't care if you're the Pope, do your own work.
>i need the code if you have then send it to me.
You've posted four times. All four posts have done nothing but beg for free code. You've been told four times that we won't give you free code. If you do it again having been sufficiently warned, I'll have you banned from this forum.
Thread locked. If anyone feels this action has been made in error, please PM me with your reasoning and I'll consider unlocking it.
We don't do work for other people. If you have a question about how to implement you program start a new thread and ask it. If you want a handout without doing any work, go elsewhere.
>When i do a for loop yes it prints the string but every word becomes a capital letter.
If you only want the first letter to be capitalized, only call the function on the first character:
char s[] = "this is a test";
s[0] = toupper ( s[0] );
printf ( "%s\n", s );
>*sPtr = toupper(*sPtr);
*sPtr = toupper ( (unsigned char)*sPtr );
Since you can't be sure that *sPtr was a character returned by a standard input function. Better safe than sorry in these situations. ;)