Tom Gunn 1,164 Practically a Master Poster

The easiest way is to sort by the secondary criteria, then sort again by the primary criteria using a stable sort algorithm. The order of the secondary criteria will stay the same with a stable algorithm.

Tom Gunn 1,164 Practically a Master Poster

All strtok does is replace the delimiter with '\0'. If you skip over it, you'll find the rest of the string:

#include <stdio.h>
#include <string.h>

int main()
{
    char s[] = "a|b|c|d|e|f|g";
    char *tok = strtok(s, "|");

    printf("%s\n%s\n", tok, tok + strlen(tok) + 1);

    return 0;
}

The only problem is there is no way to tell if strtok is finished until it returns NULL, and by then it's too late. If you know that there is more than one token, this works, but if not, you have to use something other than strtok to get the first token or do some extra testing:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char s[1024];
    char *p;

    printf("Type a sentence: ");
    fflush(stdout);

    if (!fgets(s, 1024, stdin)) return EXIT_FAILURE;
    if (p = strchr(s, '\n')) *p = '\0';

    if (!strpbrk(s, " \t\r\v")) printf("%s\n", s);
    else
    {
        char *tok = strtok(s, " \t\r\v");

        printf("%s\n%s\n", tok, tok + strlen(tok) + 1);
    }

    return 0;
}
tux4life commented: The most useful post in this thread :) +12
Tom Gunn 1,164 Practically a Master Poster

Linked lists can be sorted just like arrays as long as you only use sequential access. Pick a sort algorithm that only looks at adjacent nodes at any given time and it'll work for lists. You don't need to monkey with links either, just swap the data.

This is a program to show you the idea. It's not suitable for your problem because the sort depends on both forward and backward traversal and your lists are only forward, but it might give you some ideas:

#include <stdio.h>

typedef int (*Comparer)(void *a, void *b);
typedef void (*Swapper)(void *a, void *b);

typedef struct Node {
    int value;
    struct Node *prev;
    struct Node *next;
} Node;

void ListSort(Node *head, Comparer cmp, Swapper swap)
{
    Node *x = head;

    /* gnomesort */
    while (x != NULL)
    {
        if (x == head || cmp(x->prev, x) <= 0)
        {
            x = x->next;
        }
        else
        {
            swap(x->prev, x);
            x = x->prev;
        }
    }
}

int CompareNodes(void *a, void *b);
void SwapNodes(void *a, void *b);
void PrintList(Node *head);

int main()
{
    /* manual list for testing */
    Node src[] = 
    {
        {5}, {6}, {3}, {5},
        {1}, {3}, {4}, {6}
    };
    int x;

    /* build the first and last links */
    src[0].next = &src[1];
    src[7].prev = &src[6];

    /* build internal node links */
    for (x = 1; x < 7; ++x)
    {
        src[x].prev = &src[x - 1];
        src[x].next = &src[x + 1];
    }

    PrintList(&src[0]);
    ListSort(&src[0], CompareNodes, SwapNodes);
    PrintList(&src[0]);

    /* just a test. let the OS free memory …
Tom Gunn 1,164 Practically a Master Poster

On gcc compiler, 2nd and third printf() call taking value of i and j automatically..
but if in first printf() call ,i don't give i and j as argument then that prints garbage value..
can nyone explain it plz..

It happens to work out that way with how printf and varargs work on gcc. varargs probably look down the call stack unconditionally, and the call stack probably doesn't physically change until values are overwritten. The second call does not overwrite the two values and they stay the same for the sequential calls.

It's really pointless to explain how undefined behavior works because it could be different the next time you run the program, or in the next revision of the compiler, and certainly on a different compiler. Just don't do it. ;)

Like tux4life said, you need at least as many values as there are format specifiers in the format string. If there are fewer values than format specifiers, it's undefined behavior. There can be more values, and the extra values will be ignored without it being UB, but that will confuse people reading your code.

tux4life commented: You clarified my doubt :) +12
Tom Gunn 1,164 Practically a Master Poster

I'm a beginner and trying to convert this code in class.

It's already a class. The only difference between struct and class in C++ is the default access rights. struct is public by default and class is private.

kindly do it for me.

Sorry my friend, but it doesn't work that way here. Kindly do it yourself and everyone here will kindly help you. ;)

Tom Gunn 1,164 Practically a Master Poster

Not if you define z as I did above. Are you defining z as the total number of numbers? I wasn't, but maybe the OP was.

You're the only one who started talking about z. The OP only wanted x and y. x is the total count of random numbers, y is the count of numbers in each group. The number of groups is calculated by x/y.

I'm defining z as the number of groups, just as you did. But all it does is make the logic more complex. You have to validate z, then you have to add extra tests to make sure that partial groups don't get lost, or that too many numbers don't get printed because you rely on z. That extra work is pointless when simple logic using x and y does the job:

int i = 0,
    j = 0;

while (true)
{
    cout << lo + rand() % (hi - lo);

    if (++i == x)
    {
        cout << '\n';
        break;
    }
    else if (++j == y)
    {
        cout << '\n';
        j = 0;
    }
    else cout << ',';
}
Tom Gunn 1,164 Practically a Master Poster

I don't expect you to do the work

I mean no offense, but a lot of people around here are going to stop helping you if you don't show your code soon. It's easy to post code and prove that you are trying. It's not so easy to convince everyone that you're not looking for a free ride without proof.

you don't need my code for that, because I don't know how to display that.

niek_e's examples do what you want. If you can't get them to work, show your code and someone can help you fix the problem.

Tom Gunn 1,164 Practically a Master Poster

If you are getting errors, then you have some code, right? Somebody can help you fix them if you show the code and say what the errors are.

Tom Gunn 1,164 Practically a Master Poster

Is there a 'z' involved, as in the total number of groups?

z can be calculated using x and y, but having an actual z makes it harder to handle an x that isn't perfectly divisible by y.

jephthah commented: Bork Bork Bork +12
Tom Gunn 1,164 Practically a Master Poster

Except for deleting line 15, what Ancient Dragon wants you to do will make your code more portable. That's a good goal, but you have a real problem to fix first: integer overflow. p, r and t can't be very big before multiplying them together will overflow an int, and overflowing an int is a lot worse than all of the other stuff Ancient Dragon is worrying about.

You can work around integer overflow by not allowing it, and that means testing for overflow before it happens. Here is your code with one of those tests added:

#include <iostream>
#include <stdexcept>
#include <climits>

using namespace std;

namespace Daniweb
{
    int Product(int a, int b, int max=INT_MAX)
    {
        if (b > max / a) throw range_error("integer overflow");
        
        return a * b;
    }

    float si(int p, int r, int t, int max=INT_MAX)
    {
        return Product(Product(p, r, max), t, max) / 100.f;
    }
}

int main() 
try
{
    int p = 1000, 
        r = 1000, 
        t = 1000;

    cout << "max test = ";
    cout << fixed << Daniweb::si(p, r, t) << '\n';
    cout << "\t!passed!\nlimit test = ";
    cout << fixed << Daniweb::si(p, r, t, 1000000000) << '\n';
    cout << "\t!passed!\noverflow test = ";
    cout << fixed << Daniweb::si(p, r, t, 999999999) << '\n';
    cout << "\t!passed!\n";
}
catch (range_error& e)
{
    cerr << e.what() << '\n';
}
Ancient Dragon commented: Good point :) +36
Tom Gunn 1,164 Practically a Master Poster

What don't you understand? I could write pages and pages explaining what's happening, but that won't help as much as a pointed answer to a pointed question. ;)

Tom Gunn 1,164 Practically a Master Poster

How huge is huge? What problem are you having?

Tom Gunn 1,164 Practically a Master Poster

I have no clue as to how to start or even where to start.

Then you're thinking about it the wrong way. Whenever you get overwhelmed with a problem, the problem is too big and needs to be broken down into smaller problems. Instead of doing everything, just open and close the file. Then build on that program by reading and printing one student record. Then build on that program by reading and printing all student records. And so on and so forth.

Keep solving little problems like that and add them to the program. You'll have an easier time writing the program and you'll have more confidence that it's correct.

Tom Gunn 1,164 Practically a Master Poster

Ah so that's why %.2f wont work for scanf...

I had a lot of trouble with scanf and printf before I found out that they're not mirror images of each other. scanf doesn't use the same format string rules as printf because they have different needs and restrictions.

Anyway this a good example but its gonna make my nose bleed...
I'll try to understand this one...

Don't forget to ask questions if you need help understanding it. :)

Tom Gunn 1,164 Practically a Master Poster

Assembly::GetExecutingAssembly()->Location; will give you the full path of the running program. The 'file date' isn't specific enough. Do you want the creation time, the last read, last write? But the File class has that stuff:

String^ path = Assembly::GetExecutingAssembly()->Location;
DateTime^ fileDate = File::GetCreationTime(path);
Tom Gunn 1,164 Practically a Master Poster

The string is only a palindrome if the characters match all of the way through. Your flag should be changed in the loop if the test fails, and you can also break from the loop because there's no need to continue checking a failed palindrome:

int different = 0;

for (i=0; i < d; i++)
{
    if (str2[d-i-1] != str[i])
    {
        different = 1;
        break;
    }
}

if (!different)
    printf("palindrome\n");
else
    printf("not palindrome\n");

If the loop goes all the way to the end, it's a palindrome. Another way to do the check without the flag is to use i. If i gets to d, it's a palindrome:

for (i=0; i < d; i++)
{
    if (str2[d-i-1] != str[i]) break;
}

if (i == d)
    printf("palindrome\n");
else
    printf("not palindrome\n");
Tom Gunn 1,164 Practically a Master Poster

c++ textbook says it's fine to allocate arrays using "new".

Yeah, that's fine. What's not fine is allocating an array using new[] , then freeing it using delete :

int *p = new int[10]; // ok
delete p; // undefined. need to use delete[]

int *p = new int; // ok
delete[] p // undefined. need to use delete

int *p = new int[10]; // ok
delete p; // undefined. need to use delete[]. probably a memory leak
delete[] p; // undefined. calling delete twice

Tests show that i will not crash so that is not correct.

Testing only shows what will happen for that run. Undefined behavior can work fine one time, crash another, and send rude emails to your boss another, all without changing anything. Instead of asking what will happen, just don't invoke UB.

Tom Gunn 1,164 Practically a Master Poster

so if i never eve delete it , will it result into memory issue , specifically a segmentation fault.

Never deleting memory causes a memory leak, not a segmentation fault. A segmentation fault is when you try to access memory outside of your address space, like through an uninitialized pointer. It usually manifests as a program crash right away. A memory leak is silent and just eats up memory in the process until the computer runs out of memory and slows down or halts.

Tom Gunn 1,164 Practically a Master Poster

I generates undefined behavior. new goes with delete and new[] goes with delete[] , you can't mix them. But in practice it will cause a memory leak for the first delete, and probably also a crash when you try to delete the second time.

Tom Gunn 1,164 Practically a Master Poster

Assuming that return B; should be return ptr; , there shouldn't be a segmentation fault. The memory doesn't go away until your code deletes it. As long as you have a pointer to the memory, it's safe to access. But if you don't ever delete it, that could cause a memory leak.

Tom Gunn 1,164 Practically a Master Poster
return *output;

That line is really the whole problem. *output is not a pointer to char, it's a char. You're also trying to return a pointer to a local array. When the function returns, the local array goes bye bye and you can't use a pointer to it anymore.

Try passing the temporary array in as a parameter and return it at the end. That way you don't have to worry about it going out of scope:

char *extract(char output[11], int *pos, char *array) {
    int max = *pos + 10, 
        count = 0;

    while (*pos != max) {
        output[count] = array[*pos];
        count++;
        (*pos)++;
    }

    return output;
}

int pos = 0;
char *string = "BlahBlahBlahBlahBlahBlah......";
char output[11] = {0};

puts(extract(output, &pos, string));
puts(extract(output, &pos, string));
Hiroshe commented: Lots of help. Thanks +2
Tom Gunn 1,164 Practically a Master Poster
return getchar();

I forgot to mention, but returning getchar() is a bad idea because it's never going to be 0, and a nonzero return from main means the program failed. The best three values for returning from main are 0 and EXIT_SUCCESS for success, or EXIT_FAILURE for failure. EXIT_SUCCESS and EXIT_FAILURE are defined in <stdlib.h>.

Tom Gunn 1,164 Practically a Master Poster

Take the pattern out of it and do a simple triangle:

F
FF
FFF
FFFF
FFFFF
FFFFFF

You can add another variable that counts down without changing how the loops work in the triangle code:

for x = 1 to 6
    for y = 0 to x
        print 'F'
    print '\n'
for x = 1 to 6
    c = 'F'
    for y = 0 to x
        print c
        c = c - 1
    print '\n'

Try to take your problems and break them apart into smaller problems and you can see how to do things easier. :)

Tom Gunn 1,164 Practically a Master Poster

That's easy with the standard library:

istringstream iss(s);
vector<char> v;
string word;

while (iss >> word) v.push_back(word[0]);
Tom Gunn 1,164 Practically a Master Poster

but i thought it would be easier if there is one simple way doin like a function or somethin.

You can write your own function to do it. :) But doing it in a general way is not as easy as you thing. Removing all spaces is easy but leaving one space isn't because a space character could be more than just a single space. If you have "a\t\tb", is it right to replace it with "a b"? What should "a\t\t\nb" be replaced with?

Tom Gunn 1,164 Practically a Master Poster

No, you blurted it out in response to Hiroshe's first suggestion without waiting for the OP to ask more questions.

My post was for both of them, and anyone else reading the thread. I've learned from people who went the extra mile before and now I'm sharing the wealth.

Why not nicely pack in a parcel with automatic installers and send him on his postal address with a Project website built?

If they're still confused, then your "advanced" answer is high and dry in the land of "huh?, wtf"

And he can ask questions. That's how it works in most places. See something you don't understand, ask about it, get an answer, and learn. But here it's all about never giving away 'trade secrets' and assuming that everyone who isn't a bitter old guru is a thieving plagiarist scumbag. :icon_rolleyes:

jephthah commented: taking back some points for being completely obtuse. -2
Tom Gunn 1,164 Practically a Master Poster

I see the OP got their wish by successive approximation without having to put in any more effort.

Congrats to all :icon_rolleyes:

If the code is already there, you might as well help make it better and hope the guy learns something instead of sitting on your arse waiting for him to fail at life.

Tom Gunn 1,164 Practically a Master Poster

but are u sure that the book - "C++ Pointers and Dynamic memory management by Michael C.Daconta" is a bad book ??

I haven't read it or heard anything about it. What I meant was that it is cheap on amazon, so if it turns out to be a bad book, you don't lose much by ordering it online.

Tom Gunn 1,164 Practically a Master Poster

1. Difference between memory allocation of local and global (or other static variables)....? (or why i cant initialize a global variable more than once outside main and all other functions)

2. Holes in structures, and structures and pointers.

3. Deep concepts in pointers, objects, classes.....i mean relation between pointers and OOP.

A good book.
A very good book.
Has a few gems on what you want.
Cheap enough to get even if it's bad.

4. near, far, Huge pointers.

Memory segmentation is why those were born. Wikipedia is pretty good about explaining how each one works.

5. Some insight into how the compiler does something....

Every compiler is different, but you can't got wrong learning how compilers work in general.

Tom Gunn 1,164 Practically a Master Poster

Tutorials only go so far. You need a good book and a comprehensive reference.

Tom Gunn 1,164 Practically a Master Poster

A few more improvements to the fixed code.

#include <stdio.h>
#include <stdlib.h>

/* constants should be centralized */
#define PESO 13.170025
#define USD  0.07593

void clear(FILE *strm)
{
    int c;

    do c = getchar(); while (c != '\n' && c != EOF);
}

int main()
{
    /* double is usually a better choice than float */
    double amount;
    int choice;

    /* long strings can be broken down to avoid multiple printfs */
    /* if you don't print '\n', flush the stream */
    printf("1) USD to PESO\n"
           "2) PESO to USD\n"
           "> ");
    fflush(stdout);

    /* check input for failure */
    if (scanf("%d", &choice) != 1)
    {
        fputs("Bad input\n", stderr);
        return EXIT_FAILURE;
    }

    /* consolidate code to avoid redundancy */
    /* if you don't print '\n', flush the stream */
    printf("Enter the amount: ");
    fflush(stdout);

    /* check input for failure */
    if (scanf("%lf", &amount) != 1)
    {
        fputs("Bad input\n", stderr);
        return EXIT_FAILURE;
    }

    if (choice == 1)
    {
        printf("%gUSD == %gPESO\n", amount, amount * PESO);
    }
    else
    {
        printf("%gPESO == %gUSD\n", amount, amount * USD);
    }

    clear(stdin);
    fputs("Press <Enter> to continue...", stderr);
    getchar();

    return EXIT_SUCCESS;
}

Also there is no need for the %.2f thing, %f will do.

The %.2f thing won't work for scanf, it's only for formatting output in printf. For printf, currency converters usually stop at the 0s for precision, so %g is a better choice than %f. %f will print the maximum precision all of the time, even if it's all 0s.

WaltP commented: We don't fix people's problems for them. We HELP them fix it themselves -4
Tom Gunn 1,164 Practically a Master Poster

I don't know what signal 368 is, but if the segmentation fault is happening in list::erase(), you can search for where you call it and stop there in a debugger to see what's up. Maybe you're passing list::end() or an invalid iterator as one of the arguments.

Tom Gunn 1,164 Practically a Master Poster

Yeah thats exactly what i wanted,sad to know not possible

What you want is called reflection. C++ has a very limited type of reflection in the RTTI stuff, but it doesn't work for variable names because variable names are lost during compilation. You have to map input strings to objects like siddhant3s showed, or some other awkward workaround.

The real problem is that end users should not need to understand the workings of your code to use the program. Instead of typing 'i' and that name being a direct link to a variable in the program, I should be able to use a more abstract user variable if you want me to have that kind of control:

#include <iostream>
#include <map>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    map<string, int> userVar;
    string field;

    cout << "User variables ({name:value} {name:value} ...): ";

    while (getline(cin, field, ' '))
    {
        istringstream iss(field);
        string name;
        int value;

        if (iss.get() == '{' &&
            getline(iss, name, ':') &&
            iss >> value)
        {
            userVar[name] = value;
        }
    }

    cout << "Current user variables\n";

    map<string, int>::const_iterator 
        begin = userVar.begin(),
        end = userVar.end();

    for (; begin != end; ++begin)
    {
        cout << begin->first << ':' << begin->second << '\n';
    }
}

It's kind of like siddhant3s' code except the end user picks the names instead of the programmer. The programmer doesn't care what names are used.

Tom Gunn 1,164 Practically a Master Poster

Stupid question: if it works for set<>, why not use set<> instead of hash_set<>? I know it's the difference between a balanced BST and a hash table, but if set<> isn't too much slower you should use the way that works right now instead of fix something broken.

Tom Gunn 1,164 Practically a Master Poster

my assumption of 8 bit chars was overly simplistic and may be incorrect for some environments.

Yeah right. 8 bit bytes are the norm now. If you are using hardware that doesn't have them, you probably don't need to be taught how to fix code that assumes them. It's like ASCII. The folks using EBCDIC already know what to look for and how to fix it. ;)

The big kicker was assuming that unsigned int was 32 bits. I think it's more probable that ad hoc code for bit fiddling will find its way to a computer where ints are 16 bits than a computer with something other than 8 bit bytes. That's why I changed your unsigned int to unsigned long. unsigned long is always at least 32 bits.

the point was not to write bulletproof code, but to merely illustrate basic bit shift and mask techniques

Add union tricks and basic concern over portability to the list of jephthah/Tommy tag team teaching goodness. :) I took the time to do it well because this stuff can be used for more than just formatting IP addresses.

Besides, everyone can learn from good code. Do you know where I can find some? ;)

Tom Gunn 1,164 Practically a Master Poster

jephthah's way is the safest and most portable once you fix the nonportable assumptions:

#include <stdio.h>

#if __STDC_VERSION == 199901L
#include <stdint.h>
#else
/* change to fit the compiler */
typedef unsigned char uint8_t;
typedef unsigned long uint32_t;
#endif

#define IPV4

#if defined(IPV4)
#define NBYTES 4
#elif defined(IPV6)
#error IPV6 not supported
#else
#error No valid IP version protocol defined
#endif

int main()
{
    uint32_t ipAddress = 167840383;
    uint8_t  octet[NBYTES];
    int x;

    for (x = 0; x < NBYTES; x++)
    {
        octet[x] = (ipAddress >> (x * 8)) & (uint8_t)-1;
    }

    for (x = NBYTES - 1; x >= 0; --x)
    {
        printf("%d", octet[x]);

        if (x > 0) printf(".");
    }

    printf("\n");

    return 0;
}

The biggest assumption jephthah's code makes is that unsigned int is 4 bytes and a byte is 8 bits. If they are, the math works out, but if they are not, bad things can happen.

I fixed those two assumptions by using the explicit sized types from C99's <stdint.h>, and for everyone playing at home without a C99 compiler, I defined uint32_t and uint8_t as an example only. Don't come crying to me if unsigned char isn't 8 bits on your computer. ;)

There is another way that's easier to get right. Instead of playing with bit operators, make a union with two members. The first member is a 32 bit type and the second is an array of 4 8 bit types. They take the same memory so when you assign the …

jephthah commented: a bit overly pedantic ... but solid +12
csurfer commented: Great code there... +3
Tom Gunn 1,164 Practically a Master Poster

use string stream in general and use atoi if speed is an issue.

That's close to my advice. But I say use strtol because atoi doesn't have any error handling capability. Boost:lexical_cast and Boost::numeric_cast are even simpler than ad hoc string stream code or robust strtol code, but you have to have Boost to use them.

Tom Gunn 1,164 Practically a Master Poster

It's hard to help you fix your code if you don't show it. ;)

Tom Gunn 1,164 Practically a Master Poster

Hey,new to stl, in c array, we can declare an array like

int a[]={2,4,5,6,7,7}

how can u do it for a vector without pushing back n times???

C++0x has extended initializer lists, but current standard C++ doesn't allow it for the vector class without tricks like siddhant3s'. Boost::Assign can make it shorter than a bunch of push_back calls and save you a dummy variable at the cost of Boost. ;)

Tom Gunn 1,164 Practically a Master Poster

Have you read Beej's guide?

Tom Gunn 1,164 Practically a Master Poster

search is a standard name declared in the <algorithm> header. It's a very bad idea to use standard names even if you don't include the header because other standard headers could include it. Try capitalizing your class from search to Search, or put it in a namespace.

Tom Gunn 1,164 Practically a Master Poster

Why is it? I am probably missing something very simple here.

Something subtle, yes. References are not pointers, even though internally they might be implemented using pointers. When you have a reference to an objects, members are accessed the same way as with regular objects.

Tom Gunn 1,164 Practically a Master Poster

Open a text file for reading by making an object of the ifstream class. Once it's open and everything is good, you can use it just like cin. Objects of the ofstream class work the same way and can be used like cout:

#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream ifp("input.txt");

    if (!ifp)
    {
        cerr << "Could not open file\n";
        return EXIT_FAILURE;
    }

    ofstream ofp("output.txt");

    if (!ofp)
    {
        cerr << "Could not open file\n";
        return EXIT_FAILURE;
    }

    int input;

    while (ifp >> input) ofp << input;
}
Tom Gunn 1,164 Practically a Master Poster

I would just add more bits to the format if that's possible:

139 <tab> 1 <tab> 0 <tab> 0 <tab> 0 <tab> 1 <tab> 0 <tab> 1 <tab> 1 <\n>

You can extract the bits of a value like this:

#include <stdio.h>

void ExtractBits(unsigned long value, 
                 unsigned char bits[],
                 int sz)
{
    int x, y = 0;

    for (x = sz - 1; x >= 0; --x)
    {
        bits[y++] = ((value >> x) & 1) ? 1 : 0;
    }
}

int main()
{
    unsigned char bits[8];
    int x;

    ExtractBits(139, bits, 8);
    for (x = 0; x < 8; ++x) printf("%c", bits[x] + '0');
    puts("");

    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

There is still a problem. Your format only allows 5 bits, but the value has 8.

Tom Gunn 1,164 Practically a Master Poster

Who cares about the fact that the compiler can easier parse your code?
That's not the real reason.
The reason for using parentheses is because it's defined like that in the standard:

That's the reason why compilers have to support the syntax now, not why the syntax is the way it is.

Tom Gunn 1,164 Practically a Master Poster

I need to write these to a binary file and in binary values (139 = 00110001).

139 in binary is 10001011. Are you using a different way of encoding the value as binary? I can show you how to get the bits of a value, but that won't help if you're limited to 6 bits and the binary string is different from the actual bits of the value.

Tom Gunn 1,164 Practically a Master Poster
while (tryanother = 'y'){
if (tryanother = 'n')

The equality operator is ==. The = operator is for assignment. Those two conditions are the same as these:

while ((tryanother = 'y') != 0){
if ((tryanother = 'n') != 0)
Tom Gunn 1,164 Practically a Master Poster

this is of topic but, how come the size of thing is called an operator if it takes a parameter?

It doesn't take a parameter, it takes an expression as the operand. Expressions can be surrounded with redundant parentheses:

double d;
float f;

sizeof d; // no redundant parentheses
sizeof(f); // redundant parentheses

It's the same way with the return operator. You see people do stuff like return 1; or return(1); , but both are right because expressions can have parentheses.

When the operand for sizeof is a type, you have to use parentheses because types can be made up of more than one token and the parentheses make it easier for the compiler to parse:

sizeof(unsigned long int);
Tom Gunn 1,164 Practically a Master Poster

http://siddhant3s.googlepages.com/how_to_tell_rusted_cpp.html#SECTION00044000000000000000

That link is really opinionated. using namespace std; says that every name in the std namespace is available without having to prefix it with std:: . using std::{name}; says that only the specified name is available without a prefix. Without either of those, you have to prefix every instance of every name in the namespace with std:: .

There's no 'correct' usage. The most flexible choice is prefixing everything with std:: . That way you cherry pick which names to use and there's no chance of clashes. But it's very verbose and lines get long really fast.

For a few names used a lot, using std::{name}; is a good way to tame the verbosity of the prefix method. You know what names are prefixed and this can be put in the global scope without worrying about it:

#include <iostream>
#include <vector>

using std::cout;
using std::vector;

int main()
{
    vector<int> v;
    int input;

    cout << "Type some numbers: ";

    while (std::cin >> input) v.push_back(input);

    vector<int>::const_iterator x = v.begin();
    vector<int>::const_iterator y = v.end();

    while (x != y) cout << *x++ << '\n';
}

A better practice is putting the using std::{name}; at the top of the block you use it in. That way you still get the verbosity savings and also make accidental clashes easier to find and fix. Anything in the global scope still gets a prefix:

#include <iostream>
#include <vector>

template <class Container>
void PrintContainer(Container container)
{
    using std::cout;

    Container::const_iterator x = container.begin(); …
Nick Evan commented: Solid advice IMO +19
Ancient Dragon commented: great explanation :) +36
tux4life commented: Excellent! +10
siddhant3s commented: Well explained +14
StuXYZ commented: Good post +5
Azurea commented: Awesome explanation! Thanks! +2