deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But it still reads the hole file.

If the code you posted is the code you're running, then the file has 10 lines or less. On the off chance that I'm stupid and failed to properly compile and run your code in my head, I tested it here and it worked perfectly.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But why the break in the default is needed?

default isn't special from a syntax standpoint, it's just another case. The reason a break is required is the same reason it's required in other cases, due to the fact that default isn't required to be the last case in the switch statement. A less common but equally valid positioning is the first case:

switch (a)
{
    default:
        Console.WriteLine("We are here");
        break;
    case 1:
    case 2:
        break;
}

And there's no requirement that default not be somewhere in the middle, though it's more confusing to read, of course. The designers of C# could have added an exception such that the last case in a switch statement doesn't require a break, but that would introduce more complexity to the language, the compiler, and force programmers to learn yet another nuance. I'd guess this was the reason it wasn't added.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So how do I read only 10 line of input file.

Create a variable that counts to 10:

for (int i = 0; i < 10 && fgets(line_buffer, sizeof(line_buffer), infile); i++)
{
    printf("%s\n", line_buffer);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you post a sample of the CSV file?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just use the file name and not the full path in the query. The path without the filename would go in the connection string. Here's a working example you can use as a template if you'd like:

    Private Function CsvGenerateView(filename As String, hasHeader As Boolean) As DataSet
        Dim connectionString = String.Format( _
            "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""{0}"";Extended Properties=""Text;HDR={1}FMT=CSVDelimited"";", _
            Path.GetDirectoryName(filename), _
            If(hasHeader, "Yes", "No"))
        Dim query = "select * from [" & Path.GetFileName(filename) & "]"
        Dim ds As New DataSet

        Using connection As New OleDbConnection(connectionString)
            Using cmd As New OleDbCommand(query, connection)
                connection.Open()

                Using da As New OleDbDataAdapter(cmd)
                    da.Fill(ds)
                End Using
            End Using
        End Using

        Return ds
    End Function
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It has been 2 and a half days, my friend.

I guess I'll do some code diving then. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problem with instant/realtime updates is that they can hammer the server, and it gets worse the more notifications you offer. Your example was Facebook, but I can guarantee that Facebook doesn't have the same server and database limitations that we do, and keeping the site responsive (not to mention avoiding crashes) is somewhat important. ;)

I agree that it'd be a great feature, I'm just not sure it's feasible at the moment.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think posts with a net rating of zero should not be considered in the overall posting quality.

Just because the post has a net rating of zero doesn't negate the fact that it has votes applied. Your suggestion would take the value of votes away such that you'd be saying "someone disagrees with your vote, so your opinion doesn't matter".

Now, on the profile, n(posts voted down) is one, but when I, for example, click on the "View posts voted down" button, the post is not displayed because its net rating is zero. Please resolve this

I'll look into it, but I suspect it's more of a timing issue as the update propagates through the system. If you check back after a day and it's still not correct, let me know, because that's way too long.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is it in case of logical operators only or every binary operator??

I could have sworn I clearly said "the logical operators are short circuiting". If other operators had that behavior, I would have mentioned it. So yes, it's only in the case of logical operators (&& and ||). Technically the conditional operator (?:) is also short circuiting, but that's so obvious and intrinsic to its behavior that there's little meaning in pointing it out.

Because since i Have mentioned the brace for && operator to make it execute first..In case of other binary operators like arithmetic ones you can increase the priority by specifing braces as in case of a=4*(5+6) here + will execute first then why dosent that happen in case of && operator in my expression

I could have sworn I clearly said "it doesn't work that way", and then went on to explain how it did work with logical operators. If there's a part of my explanation you didn't understand, please point it out and I'll try to elaborate. But please don't completely discard everything I said that answered your question and then ask the same damn question again.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Athough I am specifying the braces for the && operator so that it gets executed first.

It doesn't work that way. The logical operators are short circuiting, and they always execute left to right. Those two features together mean that the left side of your || statement will always occur first. Because that test evaluates to true, there's no point in executing the right side; the final result is known, and side effects on the right side are immaterial as far as the logical tests are concerned.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I wouldn't put them on your resume, but if they're good examples of your ability I'd include them in a project portfolio for interviews.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so i am using getch(); it shows error and even for systemn("pause");

Neither of those are valid in C#, they're C/C++ functions. How are you running this program? Anyway, if you must do it, use Console.ReadKey(false) to simulate getch().

On a side note, if you're not willing to read the documentation before trying random things and then asking for help, I'm not willing to help you fix the mess you create. Keep that in mind and RTFM as a first step in troubleshooting any problem.

this is the code which i changed according to your program

Works for me.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

sum = sum + size;

This is meaningless, it has nothing to do with summing the values in the array.

sum = Convert.ToInt32(Console.ReadLine());

This is counterproductive, it destroys whatever value was already stored by sum. Look very carefully:

Console.WriteLine("the sum of elements are");

for (size = 0; size < 10; size++)
{
    sum += arr[size];
}

Console.WriteLine("sum:{0}", sum);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

please can u correct my program and tell my mistake please

If I do your work for you, you won't learn. I've already told you your mistake (you don't output the sum and you unnecessarily overwrite the sum at the end). Please refer to an earlier post of mine in this thread where I provided a correct and working snippet. Modifying it to use an array shouldn't be too difficult.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

That's because you don't output the sum...ever. In fact, you undo all of the work of the program by overwriting the sum at the end.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You don't need an array to sum numbers that are coming in sequentially, but you do need to accept those numbers properly in turn and accumulate them in the sum:

int sum = 0;

for (int i = 0; i < 10; i++)
{
    sum += Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("Sum: {0}", sum);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I had been away such a long time, i didn't ever notice when that option was added.

It's always been there. ;) Under vBulletin the feature was called thread subscription in your control panel's options section, and under Daniweb's custom system it's automatically watching articles from your edit profile page. We added that feature before the migration from vBulletin to the current system.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's certainly frustrating when I'm working with a programmer who clearly has a weak fundamentals, but I don't think "modern" languages (whatever you choose to mean by that) are the only culprit, or even the most prominent culprit. More likely is this wonderful resource we have called the internet, and the fact that one can practically cut and paste their way to a reasonably functional application with little more than a laundry list of Google queries.

It's simple evolution concerning languages that do a lot of the grunt work for you, because software is becoming ever more complex, yet our deadlines for writing it remain short, and the capacity of our brains remains limited.

deltascrow commented: I agree, though I sort of was referring to the detailed libraries given out with the language(s). Though it makes coding easier, new people tend to stop using their minds once they see the libraries. Just saying. :\ +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd suggest this tutorial as it covers a lot of information, but builds up to it with just enough code to get the job done. It's written in C, but a conversion to C++ is trivial.

Concerning your immediate problem, I notice that you never modify p, even though it being NULL or not is a key component of the algorithm. Assuming p is supposed to be your head node, that means you need something more like this to build the list in reverse:

#include <iostream>

using namespace std;

struct node
{
    int data;
    node *next;
} *p;

int main()
{
    node *tmp;

    cout << "Enter numbers (0 to stop): ";

    while (true)
    {
        int num;

        if (!(cin >> num) || !num) {
            break;
        }

        tmp = new node;
        tmp->data = num;
        tmp->next = p;
        p = tmp;
    }

    // Test the list outside of the creation loop
    for (tmp = p; tmp; tmp = tmp->next) {
        cout << tmp->data << (tmp->next ? "->" : "\n");
    }

    // Ignore list destruction for now
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

which is better for a noob programmer ? netbeans or jcreator?

While I agree with James as far as learning how things work under the hood first, it's not unreasonable to move quickly into an IDE once you get a handle on it. In that case I'd suggest JCreator as a first IDE because it's simpler (at least it was when I last looked). Once you start getting more serious, then NetBeans begins to shine as one of the better IDEs.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Adding to what sepp2k said, when you say Text foo, it's as if you said char foo[80]. A typedef represents a type, where the name of the typedef fits in the same place that the variable name would in an actual declaration. It's simpler and more consistent to keep the same declaration syntax rules.

nmakes commented: Hmm... Thank you! :D +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

By "record" I was thinking more of a structure-based solution. You'd read a line from the flat file, break it down into fields, then populate a structure with validation rules to determine if the line was legit or not. For example, using this test flat file:

12345,Joe,Blow,19,3.1
55326,Jane,Doe,20,4.0
47200,Stu,Bernstein,20,2.5
78309,Foo,McDiddles,19,1.0

You might parse and display it like this:

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

typedef struct student {
    int    id;
    char   first[10];
    char   last[50];
    int    age;
    double gpa;
} student;

int deserialize(const char *s, student *record, char *delim)
{
    char *temp = (char*)malloc(strlen(s) + 1);
    int rc = 0;

    if (temp) {
        char *tok;

        /* make a working copy because strtok modifies the string */
        strcpy(temp, s);

        rc = ((tok = strtok(temp, delim)) != NULL && sscanf(tok, "%d", &record->id) == 1) &&
             ((tok = strtok(NULL, delim)) != NULL && strcpy(record->first, tok)) &&
             ((tok = strtok(NULL, delim)) != NULL && strcpy(record->last, tok)) &&
             ((tok = strtok(NULL, delim)) != NULL && sscanf(tok, "%d", &record->age) == 1) &&
             ((tok = strtok(NULL, delim)) != NULL && sscanf(tok, "%lf", &record->gpa) == 1);

        free(temp);
    }

    return rc;
}

int main(void)
{
    FILE *in = fopen("test.txt", "r");

    if (in) {
        student records[10];
        char line[BUFSIZ];
        size_t i, n;

        for (n = 0; n < 10 && fgets(line, sizeof line, in); n++) {
            if (!deserialize(line, &records[n], ",")) {
                break;
            }
        }

        for (i = 0; i < n; i++) {
            printf("Student #%d\n", records[i].id);
            printf("\t%s, %s (%d)\n", records[i].last, records[i].first, records[i].age);
            printf("\tGPA: %1.1f\n", records[i].gpa);
        }
    }

    return 0; …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

this code kind of gives me the output i need. is there a better way to do this?

Always start with "working", then work on "better". But aside from tossing those several calls to strtok() into a loop, I'd say you're on the right track. Do you have any concerns about storing the strings in a record?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

that code is a bit more advanced

CSV is a bit more complicated, so the code to handle it must also be more complicated.

what if its just a regular csv file, no quotes.

Let's make one thing clear, when you say CSV you imply a format that includes the following restrictions (based on RFC 4180):

  1. The first line may optionally be a header.
  2. Each record is placed on a separate line.
  3. Each record contains one or more fields separated by a single comma.
  4. Empty fields are represented by two adjacent commas.
  5. Each field may optionally be surrounded by double quotes.
  6. If a field contains a newline, comma, or double quote, then the field must be surrounded by double quotes.
  7. Double quotes inside of a field must be escaped by doubling them (eg. "allowed ""'s inside").

So when you say "regular" CSV, the above is what everyone will assume. In my experience the most common CSV feature that's not included is support for embedded newlines.

You can say "simple" CSV, or CSV "without quoting rules", or even "comma delimited" to make it clear that you only support comma delimiters and none of the special rules. However, this also introduces the restriction that you cannot have embedded commas in a field. In my experience, this is often prohibitive to the point where I prefer pipe characters ('|') for simple delimited files because pipes are less likely to be in a field.

what if …

smith32 commented: that help me understand the CSV file and inspirit to learn CSV file format. Thank you a lot. +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I guess strtok can read a csv file

Only if there are no embedded delimiters in a field. strtok() isn't smart enough to determine that a field is quoted and ignore the a delimiter if it's inside a quoted field, nor is it smart enough to recognize escaped quotes.

As I mentioned before, you need to take more care in parsing the format, because it's not as simple as splitting on commas. For example:

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

char **split_csv(const char *line, char delim)
{
    char **buf = (char**)malloc(2 * sizeof *buf);
    size_t pos, n = 0, len = 0;
    int inquote = 0;

    if (!buf) {
        return NULL;
    }

    buf[n] = NULL;

    /* Trim leading whitespace on the first field */
    for (pos = 0; line[pos] && line[pos] == ' ' || line[pos] == '\t'; pos++) {
        ++pos;
    }

    for (;; pos++) {
        char ch = line[pos];

        if (!inquote && len == 0 && ch == '"') {
            /* Starting a quoted field */
            inquote = 1;
        }
        else if (inquote && ch == '"') {
            if (line[pos + 1] != '"') {
                /* Terminating a quoted field */
                inquote = 0;

                /* Trim trailing whitespace on the field */
                while (line[pos + 1] && line[pos + 1] == ' ' || line[pos + 1] == '\t') {
                    ++pos;
                }
            }
            else {
                /* The quote was escapted so it doesn't count */
                buf[n] = (char*)realloc(buf[n], (++len + 1) * sizeof *buf[n]);
                buf[n][len - …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I seem to be agreeing with deceptikon a lot lately! :-)

I'm very agreeable. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

strtok() doesn't respect CSV quoting rules, and as such it's the wrong solution to your problem. You need to actually parse the CSV format and break it down properly, which means either using a library or writing your own parser (not especially difficult, but not trivial either).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are you trying to store the music file itself as a blob, or are you storing a path for the file and relevant metadata? Because the former isn't recommended and the latter is trivial as long as you have a way of extracting the metadata.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you're using LPCWSTR in the first place, you should also be using std::wstring rather than std::string. Then you can just use the c_str() method from std::wstring directly. It's certainly possible to convert the latter into the former, but it's fair to say that not having to do a conversion is the better option if you can manage it:

#include <string>
#include <vector>
#include <Windows.h>

namespace strings {
    std::wstring widen(const std::string& s)
    {
        std::vector<wchar_t> buf(MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size() + 1, 0, 0));

        MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size() + 1, &buf[0], buf.size());

        return std::wstring(&buf[0]);
    }
}
CodeAngry commented: You should still consider checking s.empty()... and return a std::wstring() directly. +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you will, explain what "SpecialCost" is, What a "SqlDbType.Int" is and what is the purpose of the zero in the parentheses

Judging by your questions, I'm guessing you aren't using parameterized queries. The first parameter is the column name of your table. The second is the type of the table, and the third is the maximum length allowed for the value. I didn't know the setup of your table, so I made up a column name: SpecialCost. Since the type of the parameter is a fixed size, the size argument is ignored, but it's still required in the constructor call. So I just use 0 since it's the most obvious dummy default.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

' I need to say spclcost = DBNull.Value. But how do I do that?

You don't do that. You use either spclcost or DBNull.Value when assigning the database parameter. For example:

Dim parameter As New SqlParameter("SpecialCost", SqlDbType.Int, 0)

If IsNumeric(txbSpecialCost.Text) Then
    parameter.Value = Convert.ToInt32(txbSpecialCost.Text)
Else
    parameter.Value = DBNull.Value
End If

Then add the parameter to your SqlCommand object's Parameters collection. spclcost never gets assigned DBNull.Value unless you want to define it as type Object, but that would confuse the intention of the code in my opinion.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

So what is the correct syntax to assign DBNull.Value to the variable "spclcost"?

You don't do it that way. If the string is empty when you write to the database, use DBNull.Value instead of spclcost.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Does "int32.TryParse()" bring back a True/False answer?

http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx

Regarding "DBNull.Value", do I write that as

No, you use it when actually writing to the database. Your title suggests that you're writing to a database, but you're focusing on what looks like validation code that runs first.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

why is there more than one way to do something?

In any language that's suitably powerful to be called general purpose, it's pretty much impossible to avoid multiple ways of accomplishing something.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I rather like NetBeans, from the selection of free tools.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When the user bypasses entering anything within those textboxes (as they should do), what is the correct way to handle the reporting?

If null values are acceptable in the database then you can write DBNull.Value when the string is empty.

Is there a way to determine if the characters within "txbSpecialCost" are Alph or Numeric characters?

Yes, though if you're looking to validate numeric input I'd suggest either a NumericUpDown control rather than TextBoxes, or validate by trying to convert to the numeric type with something like Int32.TryParse().

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

row[2] and row[3] are already doubles

In a DataRow, they're objects. They may actually be doubles, but the immediate representation is Object as stated by the documentation for the index operator, so you must do a conversion.

Your solution is funky because double.Parse() requires a string argument. You can make it less funky by using Convert.ToDouble(), which has an overload for Object:

tempdata[i] = Convert.ToDouble(row[2]);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i declared 'n' aand 'k' global and i got success.

That means they're defaulted to 0 instead of given some random value.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In those cases either the program didn't expect input, or your code used reasonable default values. Did you try what I suggested?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

@ tinstaafl it is also working fine on my dev-c++ but why it giving RTE on ideone?

I suspect you're not giving the Ideone sufficient input to work with. Click the "upload with new input" button and add this:

5 1 2 3 4 5

There should be no errors and the output will be:

3
9
27
81
243
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I wonder is it safe?

As written it won't compile, so if you want to get technical it's perfectly safe as it'll never run. However, I suspect that you're paraphrasing. If definitions of those arrays are provided somewhere else then the code will compile and run.

Assuming a more complete example, it isn't necessarily safe because there are no provisions to avoid overflowing the arrays with a string that's too long. This is a classic problem with sprintf(), and the usual answer is snprintf(). However, snprintf() isn't a standard function prior to the C99 standard, so your compiler may not support it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Sorry dude, but I think a good lesson for you right now would be to fail miserably because you relied too much on the kindness of others in doing your work for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

ok so if use a==b instead of strcmp() this could solve the problem

Um, no. If you use a == b then you'll be comparing the address of two arrays, not the content of two strings. You do want to use strcmp(), but you want to use it correctly (as in my example), and with full understanding of how it works.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

pardon?

You don't know what indentation is?

can u tell in simple words what is the problem with my codes?

No. If you're not willing to put any effort into formatting your code so that it's easy to read, I'm not willing to put any effort into reading it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Do you seriously work with your code unindented like that? So far all of your posts have zero indentation before some kind mod fixes it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

strcmp() doesn't return a boolean, it returns a relation:

  • <0 - The first string is lexicographically "smaller".
  • 0 - The two strings are equivalent.
  • >0 The first string is lexicographically "larger".

So when you want to test for equality, it should look like this:

if (strcmp(a, b) == 0) {
    /* Equal */
}
else {
    /* Not equal */
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Line 11 of your program doesn't call the function, and as a result the compiler assumes you want that function's address. You need to include the argument list to call it:

printf("%d %d\n", n, powerof2(n));
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Though if you search through the feedback threads, I posted the complete list of automatic titles (as it was then) not long after we went live with the new system last March. I'm reasonably sure it hasn't changed.