deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Nobody is going to do your homework for you. Please read our rules and then ask a specific question about the problem if you need help. And by help, I mean a little help, not giving you the answers.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see a bunch of potential problems, but in my environment the file reads perfectly. I don't want this post to be completely useless to you, so here is a test program that just reads the file and displays the lines in the vector. I fixed the aforementioned potential problems too and noted them with comments:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

using namespace std;

vector<string> readLines(istream& is)
{
    vector<string> lines;
    string line;
    
    // Try to use the result of the input request as a loop condition
    while (getline(is, line))
    {
        lines.push_back(line);
    }
    
    return lines;
}

void displayLines(vector<string> const& lines)
{
    cout << "Displaying file contents:\n\n";
        
    for (vector<string>::size_type i = 0; i < lines.size(); i++)
    {
        cout << lines[i] << endl;
    }
    
    cout << "Number of lines: " << lines.size() << endl;
}

int main()
{
    string filename;
    
    // Use a loop, main() should not be called recursively
    while (cout << "File to read: ", getline(cin, filename))
    {
        ifstream myfile(filename.c_str());

        // istream has a conversion to boolean that looks at the state
        if (myfile)
        {
            displayLines(readLines(myfile));
        }
        else
        {
            // perror() will tell you why the open failed
            perror("Unable to open file");
        }
    }
}
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

So, std is a namespace?

Yuppers.

And how we know the syntax inside std?

I don't understand the question.

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

Do you have to be like a master programmer in a certain language to land a job in this field?

Of course not. The idea that professional developers are always masters of the craft is a romanticized fantasy that hobbyists dream up. The reality is that only a small fraction of professional developers are more than average programmers.

Mrewan79 commented: This is true. There's a lot of bluff +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

where as in .NET , AFAIK, you can code in around 56 different languages

But let's be realistic. Despite the flexibility of the CLI, how often do you see common production use of anything other than the two heavy hitters: C# and VB.NET?

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

What do you mean by "input and output all device"?

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'm unable to reproduce the issue, sorry. :(

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see a few problems with the sorting algorithm:

int p = o - 1;

When the loop first starts, o is 0, but the next thing the code does is compare values[p] with values[p + 1]. That's the same as saying values[-1] > values[0] , which is an out of bounds array access. The test for p >= 0 should come first to protect against an invalid access.

temp_upper = values[p];

temp_upper is only assigned to in the function, so this line effectively does nothing.

The algorithm looks like half of insertion sort and half of selection sort, which totals to nothing at all. ;) The process of selection sort is for each element, find the smallest or largest remaining element and swap the two. If moving from right to left, look for the largest, and if moving from left to right, look for the smallest. It looks like this for left to right:

void selectSort()
{
    // For each element in the array
        // Starting with the next element
            // Look for a smaller value
        
        // If the current element isn't the smallest
            // Swap with the smaller value that was found
}

Filling in the comments with actual code is straightforward once you understand the logic:

void selectSort()
{
    // For each element in the array
    for (int i = 0; i < arraysize; i++)
    {
        int min_index = i;
        
        // Starting with the next element
        for (int j = …
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

What kind of flexibility do you have in the file format? If it doesn't need to be human readable outside of the reading application, you could store records in the insertion order for a binary search tree. That way there's no mucking about with sorting, it all happens naturally through the tree. Updating the file is a simple matter of overwriting the it with a preorder traversal of the tree.

If you have a really large number of records, you might also consider using a database instead of a flat file for performance.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What input are you using to test?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

which is the best programming language between java and .net.

.NET isn't a language, it's a framework. You probably mean Java and C# as they're very similar in terms of syntax, but it's still impossible to compare languages without a very specific context and well defined points of comparison. Just asking which is better will get you nothing but subjective answers.

JAVA would be slower than .NET since there is a middle man (JRE). In other hand, JAVA comes for FREE..

Both points are incorrect. Java supports JIT compilation just like .NET languages, and the slowness argument stopped being valid around the turn of the millennium when Java started to really mature. Also note that .NET's CLR roughly corresponds to the JRE in terms of being a "middle man".

Like Java, .NET as a development platform including a compiler can be downloaded for free, and you can even get Visual Studio, one of the better IDEs on the market, in one of the free Express versions.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The logic for countWords is now broken because it throws away every other character.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You can initialize present to '\0'. That won't compare equal to whitespace or any of you word boundaries, and it will immediately be reset to whatever the first character is.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you say a post is good or bad, you always have to why.

Voting is completely anonymous outside of a direct database query, which only Dani presently has access to perform. With the current vBulletin back-end, reputation is not anonymous, but a comment isn't required. As best practice I'd recommend always including a comment, but there's no enforcement right now.

In the upcoming new back-end, votes and reputation are more directly related. Reputation is a specialized kind of vote that requires a comment and affects reputation points. However, votes without reputation will continue to be anonymous outside of a direct database query.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I mean you need to get a debugger and step through each line of the code as it's executing. Monitor your indexes and make sure that they're always within bounds of the array's size.

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

Or the less redundant:

repeat1 = true;

while (repeat1)
{
    cout << "Would you like to add another item? (Y/N): ";
    cin >> addAnother;
    repeat1 = (addAnother == 'y' || addAnother == 'Y');
}

Note that I fixed the condition for checking against 'y' or 'Y'. Before it used && instead of ||, and there's no way addAnother could be both 'y' and 'Y'. That was why it was always false. :) This would be a good place for toupper() or tolower():

repeat1 = (toupper(addAnother) == 'Y');
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

0xC0000005 is an access violation, so the code probably still has a problem with out of bounds indexing. The code is large, and I'm disinclined to debug it given my current workload. Have you stepped through a short run in your debugger to help pinpoint where the violation is causing the program to terminate?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What's a nod?
What's an edge?
What's a weight?

Nod is obviously a typo for node, and all of those terms are well known in graph theory, as is Prim's algorithm. I don't think the OP is expected to explain concepts that should be common knowledge, and I'm assuming you're intentionally acting dense, because your post history suggests a strong foundation in computer science.

I definitely agree with you that the OP is being lazy with this question, but I don't think it's due to not explaining what a graph is. ;)

What the **** are you asking?

He wants us to debug the program and tell him why perim() always returns 0. To which I'd ask what results he got from running the algorithm through a debugger. I'd also ask for a set of test data that produces the wrong result along with the expected result instead of just throwing the code out and hoping any helpers are interested enough to set up a realistic graph for testing.

On an amusing side note, it looks like this program is a translation of Kruskal's algorithm into Prim's algorithm, judging by the krus structure. So it's possible that the algorithm is a bastardization of both and unlikely to work at all, but I didn't look at it closely, that's just speculation. :)

WaltP commented: I'm not asking you... -4
DeanMSands3 commented: Well said, sir. +4
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here are the formulae for converting between Fahrenheit and Celsius:

Celsius = (5.0 / 9.0) * (Fahrenheit - 32)
Fahrenheit = (9.0 / 5.0) * Celsius + 32

Once you have the values for Celsius or Fahrenheit, just plug in the formula at the appropriate place and display the result.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This looks like a normal homework assignment that combines previously learned tasks into a complete application:

  • Generating random numbers
  • File I/O
  • Searching
  • Sorting

The only part that might not have been covered in your class would be computing the CPU time, but that's straightforward. I'll give you that part, as a sign of good will in the hope that you're not just looking for a hand out. ;)

#include <iostream>
#include <climits>
#include <ctime>

using namespace std;

class Timer
{
public:
    void start() { _start = clock(); }
    void stop() { _stop = clock(); }
    double elapsed() const { return ((double)_stop - _start) / CLOCKS_PER_SEC; }
private:
    clock_t _start, _stop;
};

int main()
{
    Timer timer;
    
    timer.start();
    
    for (int i = 0; i < INT_MAX; i++)
    {
        // Loopity loop
    }
    
    timer.stop();
    
    cout << "The loop took " << timer.elapsed() << " seconds\n";
}

Aside from the timing, which part of the assignment don't you understand? Just posting a homework assignment without any proof of effort comes close to breaking Daniweb's homework rule, and given the complexity of the assignment I strongly doubt that you haven't learned enough to write some basic test programs for each part.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The Programm stops at line 325 - 331

The array is being indexed with timer0, but the rest of the loop suggests that it should be using timer2. I'd guess that timer0 is out of bounds for the array, which is one of the big causes for a segmentation fault.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

C++ isn't an easy language to learn. This book is as close to a modern introduction as you'll find, but it's starting to show some age. The new standard came out recently, but I don't know of any books focusing on it yet, much less beginning books.

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

Since getch() is not and never has been part of the language definition, you should consider not using it at all.

The language definition doesn't have an equivalent, so unless you're sure the behavior isn't needed, this is a bad argument for such advice. Depending on how getch() is used, it may or may not be superfluous though. If it's superfluous then there are grounds for removing the feature entirely in favor of portability. But that's not really your call, is it? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I assume you're using a Linux system and not MinGW because MinGW's gcc supports getch(). You can reproduce the effect of getch() on Linux like this.

Arch Stanton commented: On Linux, using gcc 4.4.5; getch() works for me! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Those seniors told me the codes have many factors of "history", every line have their
"meaning", but when I ask them--those seniors of our company, they know nothing and have
not ideas what is wrong with these codes.

You're treading on dangerous ground. It's very important not to think of yourself as superior, because there's nearly always a reason behind the way code is written. The reason may be forgotten, but there was almost certainly a reason. One day you'll be on the receiving end of a bad situation and discover that your own code becomes weird. ;)

In an ideal world we would write code following best practices, but in the real world there are compatibility issues, and deadlines, and any number of factors that decrease the academic quality of our code that armchair critics looking on after the fact won't see.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

1) Other. Mostly books, reading code, answering questions about code, and experimenting.

2) Interested.

3) No, I learned C first.

4) Yes, I've learned many languages after C++.

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

gallon is used as the loop controller, but you never change its value in the loop body. This is called an infinite loop.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How is 'string' defined for this purpose? Technically any text file only has one string, the entire contents of the file. Another common method is reading words where a 'word' is any unbroken sequence of non-whitespace characters.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It alternates characters just fine for me, but you can simplify the toggle just by flipping a variable instead of trying to calculate it based on the loop indexes:

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    int basecolor1 = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
    int basecolor2 = FOREGROUND_RED | FOREGROUND_INTENSITY;
    int x, y, k = 1;
    
    for (x = 0; x < 4; x++)
    {
        for (y = 0; y < 4; y++)
        {
            if (k == 1)
            {
                SetConsoleTextAttribute(hcon,(int)(basecolor1));
            }
            else
            {
                SetConsoleTextAttribute(hcon,(int)(basecolor2));
            }
            
            cout << k;
            k = !k;
        }
        
        cout << endl;
    }
}

If that's not the output you want, please describe exactly what it should look like.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The standard uses a simpler description:

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ok..then
c=++a + ++a + ++a
should give the output c=24
but its c=22.
???

Undefined behavior is the Schrödinger's cat of programming. The result of an undefined expression could be anything until you actually run it, and the result you get in practice depends on too many factors to be predictable. Results that aren't predictable and can't be controlled are undesirable, right?

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

I still am not able to figure out at what times the File.Delete() fails... As it happens with some files and not with others.

It's not necessarily the files themselves, but processes holding an open handle to them. I've had luck with the following type of class in cases like this:

public static class SafeFile
{
    public static void Delete(string path)
    {
        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }

    public static void TimedDelete(string path, int msPause)
    {
        if (!File.Exists(path))
        {
            return;
        }

        for (int tries = 0; tries < 3; tries++)
        {
            try
            {
                Thread.Sleep(msPause);
                File.Delete(path);

                // No exceptions; assume successful deletion
                break;
            }
            catch
            {
                // Try again
            }
        }
    }
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There's no choice but to use a loop somewhere. You can hide it behind a function, or use a compiler-specific function like strlower(), but there's still a loop.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just one final question for my understanding.
Can anyone explain to me what the arguments in the for loop?

for (char *p = strtok(str, fmt); count < MAX && p; p = strtok(0, fmt))
    {
        strcpy(strWords[count++], p);
    }

strtok() has two steps: set the source string/return the first token, and return subsequent tokens on the source string. Because strtok() stores a pointer to the source string internally, any subsequent calls after the first must have a source string of NULL. The pattern looks like this:

char* tok;

tok = strtok(source, delim);

while (tok != NULL)
{
    // Use tok

    tok = strtok(NULL, delim);
}

The first thing I did was merge that into a for loop to make the unusual behavior of strtok() more clear:

for (tok = strtok(source, delim); tok != NULL; tok = strtok(NULL, delim))
{
    // Use tok
}

Then I replaced NULL with 0 because that's the convention in C++. In the new standard, nullptr is recommended. I also removed the redundant test against NULL in the loop condition because it happens implicitly just by using tok. Finally, I defined tok as local to the for loop by declaring it in the initialization clause:

for (char* tok = strtok(source, delim); tok; tok = strtok(0, delim))
{
    // Use tok
}

That's for the use of strtok(). The extra test of count < MAX just makes sure that the loop doesn't try to call strcpy() on an index that doesn't exist if there …

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

What does your manipulator look like?

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;
    }
}