deceptikon 1,790 Code Sniper Team Colleague Featured Poster

An easy way to use variadic template functions is with direct recursion:

#include <iostream>

using namespace std;

void foo()
{
    // Base case for variadic recursion
}

template<typename T, typename... Args>
void foo(T first, const Args... remaining)
{
    // Use the first argument
    cout << first << endl;
    
    // Recursively pass on the remaining arguments
    foo(remaining...);
}

int main()
{
    cout.setf(ios::boolalpha); // To make bool args print right
    
    foo(1, "test", 3.14159, 'Q', true, 6);
}
triumphost commented: Doesn't work but thanks anyway Rep+1 +6
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's not possible without writing your own preprocessor that adds appropriate escape characters for the stringizing operator.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

and how does user signals EOF (sorry a newbie!...)?
I suppose by pressing Ctrl+c or forcibly ending the program.
Please correct in case i am wrong.

It depends on the operating system, but Windows uses ctrl+z and Linux/Unix-based OSes use ctrl+d. Those two are the most common; let me know if you're not using either of them.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It will go on forever unless the user signals EOF or there's a stream error of some sort.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have been trying to take input until empty string is entered(simply press enter) ?

The >> operator doesn't recognize whitespace except as a delimiter on both sides. If you just press enter, it's ignored while the >> operator waits for non-whitespace. To check for a blank line you would use getline():

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string buff;
    
    while (getline(cin, buff) && !buff.empty())
    {
        cout << "'" << buff << "'" << endl;
    }
}

But that doesn't have the same behavior as the >> operator if you want to read words instead of lines. What kind of behavior do you want for user input?

The extraction operator returns a reference to the stream, not a boolean value.

But the stream object has a conversion to boolean when in boolean context. Prior to C++11 the conversion was to void* and then to boolean from there, and in C++11 there's a direct conversion to bool.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think the calculations are too complicated. Try this:

// Get the total months for full years worked
tm = (eyear - syear) * 12;

// Remove months not worked from the first year
tm -= (smnt - 1);

// Add months worked from the last year
tm += emnt;
    
cout << " years " << (tm / 12) << " months " << (tm % 12) << endl;

There are a number of ways to handle the odd months, the above assumes that the edge months are inclusive. So if the starting date was 1-31-2003 and the ending date was 12-1-2003, it would still come out to a full year of employment. To get more precise you would need to include days, or make an assumption about how many days are worked in those two months.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

did I miss something here??

There are too many variables named t. There's the global t and the local t in main()'s loop. It's recommended not to use the same name more than once for nested scopes. It's very easy to get confused.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it possible that multiple instances of a function can exist?

Yes:

fact(5);
fact(5);

Those are two instances. It would help to learn how function calls are typically handled if you don't know already. Knowing about the call stack helps to differentiate between definition of a function and execution of it at run time.

It basically keeps calling the method until n is equal to 1 as we have set the IF condition and then it reverse evaluates the factorials until it reaches the factorial of 4 and then finally multiply it by 5 in order to give 120.

Well, I can't say that's wrong. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The way I see things, constantly calling fact(n - 1) when the method tries to return will result in an infinite amount of times the method being called without returning anything.

Each call invokes a new instance of the function with new arguments. The effect is as if you did this:

int fact1()
{
    return 1;
}

int fact2()
{
    return fact1() * 2;
}

int fact3()
{
    return fact2() * 3;
}

int fact4()
{
    return fact3() * 4;
}

int fact()
{
    return fact4() * 5;
}

Recursion just makes the syntax for that process simpler.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but if I don't use stdafx. vs would give me a precompiled header error.

You can turn off precompiled headers in the project settings.

it is a win32 console project..

Anything except an empty project will add Microsoftisms. When you're trying to write portable code, I'd recommend starting with an empty project.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Only Dani can undo reputation, to the best of my knowledge, as it's not built into the vBulletin interface even for community admins. However, you can negate it by waiting until tomorrow and then applying positive rep to another post. It's not perfect, but at least that would make the net effect on his reputation points zero.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
istream& my_getline(istream& is, string& s)
{
    istream& result = getline(is, s);

    if (!result.eof())
    {
        s.push_back('\n');
    }

    return result;
}

Presto magico!

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there any other function that would including the end line character?

istream& my_getline(istream& is, string& s)
{
    istream& result = getline(is, s);

    s.push_back('\n');

    return result;
}

Presto!

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
template<typename T>
Point<T> Point<T>::plus(Point<T> operand2) {
	Point temp;
	temp.set_x(get_x() + operand2.get_x());
	temp.set_y(get_y() + operand2.get_y());
	return temp;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're probably using cin like cin >> s . That method stops reading at whitespace, so s is only populated with the first word from input. If that's the case then it has nothing to do with how the code copies to the clipboard, and you can fix it by reading a line with getline():

if (getline(cin, s))
{
    // Copy s to the clipboard
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's only a partial test. A string can contain only digits and still be out of range for the target type. If it's out of range, trying to convert the string to the target type will be undefined.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there any way by which we can debug both child and parent proccess just the normal program.

Assuming you're debugging with gdb: http://www.delorie.com/gnu/docs/gdb/gdb_26.html

fork returns two values ,0 for child process, and pid of child for parent process. Hence , your if is always true and it runs for parent. If you want some code to run for child you will have to check

if(fork() == 0){
// your code
}

All you did was reverse the test. if (fork()) is equivalent to if (fork() != 0) .

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't think we really disagree, we're just thinking on different levels. A big difference between two operations from the perspective of the CPU will nearly always be negligible from a user perspective unless it's performed a large number of times. The time it takes to load individual variables from memory into a register will be overwhelmed by the myriad steps performed in an algorithm. That's why it's best practice to focus on optimizing your algorithms' logic first before trying to micromanage things that will have far less impact.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does the string represent a valid double value? If not, then you won't find a conversion function that works without first getting a library that supports larger floating point values.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I need to know which of these three copies of code is considered best.

const variables are preferred over macros because their names aren't lost during preprocessing. One of the biggest problems with macros is difficulty in debugging code where a macro is involved. Making const a compile time constant was intended to replace non-function-like macros.

When defining a set of related constants, enumerations are preferred because it makes your intentions clear and offers language support for treating the constants as a proper collection. If you use const variables or macros, the onus is completely on the programmer to make sure that the constants are used as intended.

I also need to which one is more efficient memory wise and which is more efficient time wise.

There's not going to be a significant enough difference for you to worry about it. Don't sweat the small stuff, data structure and algorithm choices make up the lion's share of performance and storage costs.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If there are more reads than writes, any reads beyond the number of writes will fail.
If there are more writes than reads, nothing happens aside from a risk of lost data for the writes that weren't consumed.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Now i know what is cout for but what is std and what are these "::" for?

The :: operator is called the scope resolution operator. It's primarily there for accessing names declared in a namespace or class, and std is the C++ library's namespace. std::cout says to look for cout in the std namespace and fail if it's not there.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think a good question to ask is why do you think you need this behavior? Even in C# it's recommended to avoid ArrayList in favor of the more statically typed generic List<>. C++ isn't designed with a universal Object class that everything derives from, which makes a heterogeneous collection awkward on top of the usual risks.

But if you really need it, look into the Boost libraries. The Boost::any type would probably be what you want.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thanks for the reply WaltP, but I don't have an .EXE file. I'm running a.out from the terminal in order to execute my program.

a.out is the executable file. Look in the same directory as a.out, or the current working directory when you run your program.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In the sense - the flexibility and the kind of apps you can develop

Then they're about the same.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As the title says, Python or Ruby?

In what context? For what purpose? What metrics are you looking to compare? It's impossible to compare languages without a very specific target of comparison. Just asking "which is better?" will get you nothing but useless subjective opinions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The only real duplication you have is in printing the too many days error. Any other overcomplication comes from parsing two dates at the same time. I think a better option is a function that parses one date, then call it twice.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's probably safer to say that there's hidden initialization and termination code in your program's executable. While it's correct to say that main() is the starting point for a program, it's not necessarily the first starting point. When your executable is loaded into memory, the starting address is probably at mainCRTStartup() instead of main().

myk45 commented: Thanks! +6
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

wordCount() is ruining the string for later processing. Always remember that strtok() modifies the string by writing '\0' at appropriate places. What about merging the two tasks of counting words and saving them to the array?

#include <iostream>
#include <cstring>

using namespace std;

namespace
{
    const int MAX = 100;
    const int LEN = 100;
    const char* fmt = ".,? ;";
}

int main()
{
    char strWords[MAX][LEN];
    char str[LEN];
    
    cout << "Enter a string: ";
    cin.getline(str, LEN);
    
    int count = 0;
    
    for (char *p = strtok(str, fmt); count < MAX && p; p = strtok(0, fmt))
    {
        strcpy(strWords[count++], p);
    }
    
    cout << "No of words = " << count << endl;
    
    for (int i = 0; i < count; i++)
    {
        cout << strWords[i] << endl;
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A busy wait loop will task the CPU while putting the thread to sleep will not. If you need a short sleep to let the connection close completely then Thread.Sleep() is the way to do it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The C++ runtime eventually has to call your main(), but there's stuff that needs to be done both before and after. Judging by the name, you're using a Microsoft compiler. If you have the CRT sources then look for crt0.c, it's a small source file that does the runtime initialization.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When you say ch=i++[s]; it means ch=(i++)[s]; , but when you say ch=++i[s]; it means ch=++(i[s]); . It's totally confusing because intuition says it should be ch=(++i)[s]; . But that's where the '!' is coming from. i is 3 at that point, and the next character after ' ' in ASCII is '!'.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

%s prints the whole string. If the starting point for the string steps ahead by one character each iteration, you basically chop off the first character each time.

char const* x = "Alice";

printf("%s", x); // "Alice"
++x;
printf("%s", x); // "lice"
++x;
printf("%s", x); // "ice"
++x;
printf("%s", x); // "ice"
++x;
printf("%s", x); // "ce"
++x;
printf("%s", x); // "e"

By the way, this line:

*x=x[n];

is very bad. x is a pointer to a string literal, and string literals are not allowed to be modified. But that statement tries to overwrite the first character of the string literal with the last.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is a stupid question, but taking my example above, are you making sure that $foo contains the value you expect?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If the checkbox should be checked, add checked="checked" to the input tag attributes:

<input type="checkbox" name="foo" value="1" <?= $foo ? 'checked="checked"' : '' ?> >
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The for loop is completely nonsensical. It's like this:

for (initialization; condition; increment)
{
    body
}

Where the roughly analogous while loop is:

initialization

while (condition)
{
    body
    increment
}

So your loop, for(i<=5&&i>=-1;++i;i>0) printf("%u",i); would look something like this while loop:

i <= 5 && i >= 1;

while (++i)
{
    printf("%u", i);
    i > 0;
}

Doesn't make much sense, does it?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

arrays decay into pointers..

Only most of the time. A common misconception is that arrays are equivalent to pointers because of that behavior.

If we consider..
int a[20];
'a' represent the starting address of the array which indeed means that it is a pointer..

http://www.torek.net/torek/c/pa.html

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this correct?

Yes, that's the biggest reason why vectors are recommended over arrays.

If this is correct even arrays size in c can be manipulated using realloc() function..

Arrays and pointers are different. realloc() only works with pointers that were previously allocated memory by malloc(), calloc(), or realloc(). Arrays have a compile time fixed size.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are arrays and vectors the same?

No.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when they click the link is the form data submitted?

No. At its simplest you would put a submit input field in the form. Then when the submit button is clicked, the form data is posted:

<form name="passvalue" action="myscript.php" method="POST">
    <input type="hidden" name="title" value="<?php echo $title ?>" />
    <input type="submit" name="submit" value="Click to Submit" />
</form>
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I saw this example while i am searching about vectors..

vector<double> student_marks;
    // no size specified: vector contains
    // no elements
 
int num_students;
cout << "Number of students: " << flush;
cin >> num_students;
 
student_marks.resize (num_students);
 
for (vector<double>::size_type i = 0; i < num_students; i++)
{
    cout << "Enter marks for student #" << i+1 
         << ": " << flush;
    cin >> student_marks[i];
}

cant we use

for (int i = 0; i < num_students; i++)

instead of

for (vector<double>::size_type i = 0; i < num_students; i++)

thanks in advance

num_students is an int, so you shouldn't use vector<double>::size_type. size_type is an unsigned type, and int is signed. It's not usually a good idea to mix signed and unsigned types.

If you use the size of the vector as a loop condition instead, then size_type would be best:

for (vector<double>::size_type i = 0; i < student_marks.size(); i++)
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How are you submitting the form?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

and even is it that turbo c supports less graphics other than the other softwares?

Sorry, I'm done with this thread. There must be a language barrier, because you don't seem to understand a thing I'm saying.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so its not preferable to use the odd combinations..

...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what's the difference of using turbo c and the other softwares for writing the program?

Compilers are designed to target an OS. If the OS dies or is too outdated to be useful then the compiler that targets it shares the same fate. Turbo C was designed for MS-DOS. If you're not using MS-DOS, you shouldn't use Turbo C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Then its preferrable to use other softwares other than turbo c?

I don't see how we're back to this, but yes, it's preferable to forget Turbo C exists.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is this a predefined one ?

I don't know what you mean by 'predefined', but that's just an example of how mixing two different heaps will blow up in your face. It's an empirical proof of this statement: 'The data structure used to store and manage allocated memory might be different between malloc()/free() and new/delete. If you mix them, the pointer might be valid with one but not the other and your program will probably crash.'

where did u use malloc or new in this code?

Nowhere, because they weren't relevant to the point of the code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

are they portable?

No less portable than Turbo C.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

the one u explained is a predefined one or just an example?

I don't understand the question.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it an old idea to compile and run c programs on turbo c?

Yes, by about 15 years. Visual C++ is freely available, Code::Blocks comes with a recent gcc build, and I hear Pelles C is good too. There are more, but those are the three most common recommendations.