Narue 5,707 Bad Cop Team Colleague

If you don't understand the requirements, ask a specific question instead of vague requests for "hints" and "help".

i am the first year student in the programming course.i am absolutely not understand it.

Teachers don't give an assignment without first covering the necessary material in class for completing the assignment. If you didn't pay attention in class and are now clueless as to how to do your homework, that's your own damn problem.

Narue 5,707 Bad Cop Team Colleague

No effort == no help.

kthxbye.

Narue 5,707 Bad Cop Team Colleague

All my local variable are initialized though..

Then you must be imagining the error. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

Threads merged.

Narue 5,707 Bad Cop Team Colleague

Here's a hint: subtract '0' from each digit in the string and you'll get the integer value of the represented digit. In other words, '0' - '0' is 0, '1' - '0' is 1, etc...

From there it's a simple loop over the string and assigning the result to your integer array.

Narue 5,707 Bad Cop Team Colleague

Access violation reading location 0xcccccccc.

Look for an uninitialized local variable in your debugger.

Narue 5,707 Bad Cop Team Colleague

I kind-of get the impression this is a dynamic-allocation-related assignment

It's not obviously homework, but even if it were, we would be doing the student a disservice by not mentioning the better alternative for future projects.

Narue 5,707 Bad Cop Team Colleague

I hear it's technically legal under newer standards, but not every compiler supports the newer standards yet.

Not in C++. The current C standard (C99) supports variable length arrays, but they're an abomination and shouldn't be used. C++ doesn't support variable length arrays in any form because the standard library handles all but the most niche of VLA use cases.

To have a truly reliable (portable) implementation, it's better to explicitly use dynamic allocation.

Or implicitly use dynamic allocation with std::vector. You're doing the same thing with fewer features and a greater chance of implementation bugs.

Narue 5,707 Bad Cop Team Colleague

Done.

Narue 5,707 Bad Cop Team Colleague

Here's a novel idea: tell us what the various errors are. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

c# - How can I raise an event every day 12:00 AM or specific time interval in c#.NET

Does nobody read the documentation? I mean, that's a classic RTFM type of question.

Narue 5,707 Bad Cop Team Colleague

does this works in turbo c?

Change the name of the compiler to whatever you want.

am not sure that "gss" is used in turbo c

"gcc" refers to the GCC compiler.

My sir said once about this as it will be in visual c++

Visual C++'s compiler is called cl.exe.

well Narue what is 'cmd' in this code?

A string! Read up on sprintf(). The idea is that we need to build a command line statement that invokes a compiler with the specified file name.

I tried it but its saying "undefined symbol".

Duh. I posted a snippet, it's your job to fill in the blanks and make it compilable.

Narue 5,707 Bad Cop Team Colleague

Yes I know.

Clearly not. Might I suggest $man man ? Then you'll see the -k and -K options which will help you search for a keyword.

Narue 5,707 Bad Cop Team Colleague

Run the man program on Linux your system, it searches for documentation. Libraries in particular are found in section 3.

Narue 5,707 Bad Cop Team Colleague

Can we (compile and execute) or just execute a c file from another c file?

Yes. The easiest way would be to simply execute the compiler with the source file as input:

sprintf(cmd, "gcc %s", filepath);

system(cmd);       /* Compile */
system("./a.out"); /* Execute */

Otherwise you're looking at running the code through an interpreter of some sort, which could be as simple as using an existing interpreter similar to above, or writing a form of eval() that handles C code (not a task taken lightly).

Ultimately, I'd say that C probably isn't the correct choice of language if dynamic evaluation of code is a necessary feature.

Narue 5,707 Bad Cop Team Colleague

I'd recommend this one, but I'm also just a little biased, having written it. ;)

Narue 5,707 Bad Cop Team Colleague

All of those are defined or typedef'd types. Are you including the appropriate headers? <time.h> and <stdbool.h> are the ones you're looking for, assuming C99.

Narue 5,707 Bad Cop Team Colleague

I was just testing you to see if you did too

Silly dragon, how many times have you seen me not know something about C? ;)

Narue 5,707 Bad Cop Team Colleague

There's not any alternative I'm aware of.

Narue 5,707 Bad Cop Team Colleague

Can that cause problems?

<sarcasm>
No, we just arbitrarily picked something to bash because it makes programming seem more like a voodoo art. :icon_rolleyes:
</sarcasm>

I should declare local variables instead?

You should declare variables with the smallest scope possible.

Narue 5,707 Bad Cop Team Colleague

Anyway, about the global variables, is that a wrong method?

Variables should have the smallest scope possible. Global variables are especially troublesome because they're visible and usable across the entire program, even areas that don't need access.

Narue 5,707 Bad Cop Team Colleague

Case matters in C. Both printf() and scanf() are all lower case, you're trying to use functions that don't exist.

Narue 5,707 Bad Cop Team Colleague

I am pretty sure that I'm not doing something wrong with this code.

You forgot to include <string>, and the code also does nothing with user after the input call. The following offers some corrections, though your use of global variables is still questionable:

#include <iostream>
#include <string>
 
using namespace std;
 
int money = 1000;
string user;
 
int main()
{
    cout << "Enter username." << endl;
    cin >> user;
    cout << "Welcome, " << user << "!" << endl;
    cout << "You have : " << money << " dollars left.\n" ;
}
Narue 5,707 Bad Cop Team Colleague

The string still must be null-terminated, which is why I suggested flooding the entire buffer with '\0' before doing anything.

The string is null terminated. strcat() properly appends a null character to the destination, so the only issue is making sure that the string is null terminated before the first call to strcat().

And you need to add 1 to n in the malloc line.

Yes indeed.

Narue 5,707 Bad Cop Team Colleague

Both issues can be solved at the same time by calling memset() to flood the array with '\0' bytes.

or a simple loop for (i=0; i<n+1; i++) p = 0;

All that's necessary is to set the first character to '\0' to make it a valid string for strcat():

p = malloc(n);
p[0] = '\0';

strcat() will then ensure that the result is properly terminated for printf().

Narue 5,707 Bad Cop Team Colleague

A function name basically evaluates to a pointer. However, don't quote me on that.

That's a reasonably accurate statement. You can only do two things with a function: call it and take its address. If you're not calling it, then you're taking its address, and the result is a pointer to a function. The only sticky area with saying that a function name evaluates to a pointer is that compilers aren't required to treat the function name in a call as a pointer.

Converting this:

foo();

to this:

(*foo)();

while legal in C, would add an unnecessary level of indirection (assuming it's not optimized away). So you probably won't see compilers treating functions as pointers internally for a call, but conceptually it's OK because the behavior is consistent with that practice.

Anyway, my reason for posting is to add a few things. First, because you can only do two things with a function, the dereference is unnecessary. The compiler will see your function pointer as such and dereference automatically if it's a call:

int (*p)() = fun;

p(); /* OK */

Second, int fun(); isn't a prototype, it's an old-style declaration. There's a subtle but significant difference in that a prototype does argument list checking while an old-style declaration does not. This applies to both the function pointer type and the actual function:

int fun();
int (*p)() = fun;

fun(123); /* Aroo? Compiles fine */
p(123);   /* Aroo? Compiles fine */
int fun(void); …
Narue 5,707 Bad Cop Team Colleague

The problem is that I don't know how many integers in the string would be otherwise I would have used sscanf with a format specifier.

strtok() would be the easiest option, but you also need to keep in mind having sufficient memory to hold the integers. If the amount is unknown then you need some way of dynamically growing an array or list. For example:

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

char *copy_string(const char *s)
{
    char *copy = malloc(strlen(s) + 1);
    
    if (copy != NULL)
        strcpy(copy, s);
        
    return copy;
}

int *isplit(const char *s, int *size, const char *delim)
{
    char *copy = copy_string(s);
    int *result = NULL;
    
    *size = 0;
    
    for (char *tok = strtok(copy, delim); 
         tok != NULL; 
         tok = strtok(NULL, delim))
    {
        // Omitting error handling for brevity
        ++(*size);
        result = realloc(result, *size * sizeof *result);
        result[*size - 1] = atoi(tok);
    }
    
    free(copy);
    
    return result;
}

#include <stdio.h>

int main(void)
{
    const char *src = "10 20 12 4 2 1 4 2 12 32";
    int size;
    int *nums = isplit(src, &size, " ");
    
    for (size_t i = 0; i < size; i++)
        printf("%d\n", nums[i]);
        
    free(nums);
    
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

You can try this : printf ( " %f \n " , 7 / 3);

This will return 2.3333..

Please explain how that's supposed to work. The expression is still in an integer context, which means the result is an integer type. You then pass this integer type to printf() with the %f specific that expects a floating-point type.

So aside from the original bug, you've introduced another: passing the wrong type to printf(). The output is more likely to be 0.000000, but since this is undefined behavior in the first place the behavior is completely unpredictable. However, 2.333333 is the least likely result due to stacking undefined behavior on top of evaluating 7/2 in integer context.

Narue 5,707 Bad Cop Team Colleague

Narue can u please explain me in detail

I don't think I can be any more clear. Use CSV to store your database records. This removes the need to convert the database between some ad hoc internal format and CSV for the import/export operations. You can still use a .txt or .bin extension with CSV content.

Narue 5,707 Bad Cop Team Colleague

7/3 is evaluated in an integer context, which means all precision is truncated to 0 when you assign to the float variable. Make either one of the operands floating-point and you'll get what you want:

a = 7.0f / 3;
Narue 5,707 Bad Cop Team Colleague

@Narue: Is there a way I can use toupper() with a string then?

Yes, the way you do everything with each character of a string: use a LOOP!

int i;

for (i = 0; line[i] != '\0'; i++)
    line[i] = toupper(line[i]);
Narue 5,707 Bad Cop Team Colleague

You are trying to print a character as a string:

printf("your quote was : %s",ch);

I'm not sure why toupper doesn't work with my IDE but try this:

printf("your quote was : %s",toupper(line));

toupper() returns a single character...

Narue 5,707 Bad Cop Team Colleague

While fgets() suggests reading from a file, you can pass stdin as the stream for user input.

Narue 5,707 Bad Cop Team Colleague
printf("%s\n", "hai welcome..." + 3);
Narue 5,707 Bad Cop Team Colleague

Can you be more specific? "Leaving the first three characters" is ambiguous. Do you want to print only the first three characters of a string, or all characters except the first three?

Narue 5,707 Bad Cop Team Colleague

YOU are telling as though iam not trying any thing

You're were acting as if you weren't trying anything.

i dont know what to do???

Check the tool chain path within the compiler options and make sure it's set up correctly? I'm going to go out on a limb and guess that you installed codeblocks-setup.exe rather than codeblocks-mingw-setup.exe. The former only installs the IDE while the latter also installs MinGW for the compiler and tools used by the IDE's default settings.

Narue 5,707 Bad Cop Team Colleague

Why not just store the file as CSV? Then export is a simple file copy, and import is a copy after verifying that the import file is in the correct format.

Narue 5,707 Bad Cop Team Colleague

How do you block the user to only enter a number for example 1 to 6?

You write your own raw input handler to read keystrokes and interpret them as desired. It should go without saying that this is terribly confusing unless you own the canvas[1] or are taking input from a GUI[2]. A much easier and more user-friendly method is simply to allow the user to type whatever he or she wants, then validate it and respond accordingly:

#include <iostream>
#include <stdexcept>
#include <boost/lexical_cast.hpp>

int main() try
{
    int value;
    
    while (true) {        
        std::cout << "Enter a number from 1 to 6: ";
        
        std::string line;
        
        if (!getline(std::cin, line))
            throw std::runtime_error("Invalid input");
        
        try {
            value = boost::lexical_cast<int>(line);
            
            if (value >= 1 && value <= 6)
                break;
            else
                std::cerr << "Out of range\n";
        } catch (boost::bad_lexical_cast&) {
            std::cerr << "Invalid number" << '\n';
        }
    }
    
    std::cout << "The square of " << value << " is " << value * value << '\n';
} catch (std::exception& ex) {
    std::cerr << "Fatal error: " << ex.what() << '\n';
}

[1] ie. You're using a "primitive" graphics engine such as curses to draw in the console.
[2] In which case you should be using an appropriate input control for numeric values rather than straight text.

Narue 5,707 Bad Cop Team Colleague

It's possible to "catch" a segmentation fault with a signal handler, but you can't resume the program after the handler runs, so it's not very useful other than terminating gracefully. In your case the better option is to fix the bug that caused the fault in the first place. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

Since this isn't an assignment, the correct answer is to ditch that piece of shit compiler and get something from the current decade. You'd have no end of troubles using a 16-bit compiler on a modern 32 or 64-bit OS anyway (the environment 99.99% of Turbo C folks are trying to run under), so this would be an exercise in unnecessary frustration.

Narue 5,707 Bad Cop Team Colleague

I mean you started two closely related threads on the same program. There's no need for two separate threads which ultimately would result in duplicated effort by the helpers.

Narue 5,707 Bad Cop Team Colleague

Threads merged.

Narue 5,707 Bad Cop Team Colleague

i dont know the actual procedure please help me .please tell the procedures to run program in eclipse or codeblocks

RTFM. Seriously, there's a point where people will stop helping you because they don't want to regurgitate the documentation that you should have read in the first place.

Narue 5,707 Bad Cop Team Colleague
fscanf(fp, "%d", &temp);
if(temp!='\n')

This is an impossible case unless one of the numbers happens to match the numeric value of '\n', and if that happens you'll get unpredictable behavior. You told scanf() to read integers, and it will discard all whitespace in the process.

What you need to do is read the file line by line, then split up each line into fields for your array:

#include <stdio.h>

int main(void)
{
    FILE *in = fopen("test.txt", "r");
    
    if (in != NULL) {
        char line[BUFSIZ];
        
        while (fgets(line, sizeof line, in) != NULL) {
            char *start = line;
            int field;
            int n;
            
            while (sscanf(start, "%d%n", &field, &n) == 1) {
                printf("%d ", field);
                start += n;
            }
                
            puts("");
        }
        
        fclose(in);
    }
    
    return 0;
}

Be mindful of the sscanf() loop in that example, because it uses a somewhat tricky way of stepping through the string. If you don't save the number of characters that were extracted and move forward accordingly, the loop will be infinite. For example, this is the wrong way:

while (sscanf(line, "%d", &field) == 1) {
    printf("%d ", field);
}

sscanf() isn't smart enough to use anything but the string you give it as the source, so this loop will continually extract the first field in line . Contrast this with something like std::istringstream in C++, where the buffer is updated internally to reflect extractions.

An alternative is to avoid sscanf() entirely and do the conversions yourself. This is more of a manual parse:

zeroliken commented: well said +3
Narue 5,707 Bad Cop Team Colleague

are there any tools that run c and c++ in windows 7???

Just about everything except Turbo C++. You made a beeline for the worst possible compiler, congratulations. :icon_rolleyes: Try Code::Blocks or Visual C++ 2010 Express for two modern compilers that run well on Windows 7.

Narue 5,707 Bad Cop Team Colleague

The good news is that if you're using a hardware scanner, the hard part is already done: the scanner will recognize and translate the contents of the barcode into a string.

The bad news is that barcodes don't typically contain the price of an item, they use an UPC/EPC encoding such that the item can be looked up in a database. Once you have the product code from your scanner, you'll need to do a search of prices from retailers for that product code (because they'll use different prices). Or if you're writing code for a specific retailer, simply query the internal product database for that product code to get the current price information.

Narue 5,707 Bad Cop Team Colleague

Would the last line work?

No.

Or would I have to declare a function to execute that last line?

Yes. However, note that you can initialize sasd to that expression in the global scope:

int vap = 7;
int pav = 2;
int sasd = vap * pav;
Narue 5,707 Bad Cop Team Colleague

i know that there is no database connection with c

Not standard C, but there are libraries for pretty much every database package out there. If you're planning on writing your own database rather than connecting to a database package, here are a few thoughts to get you started based on your list of required tasks:

  • add: When adding, keep in mind the cost of searching, because finding a record quickly is key in editing, deleting, and (obviously) searching. This means that you shouldn't just append new records to a file, there should be some kind of method to the madness of how you organize both the files and contents of each file.

    Also note that if the database is to be scalable, you'll want a structure that supports breaking records up into multiple files instead of just one monolithic file. However, if it's just an ad hoc database that won't even be complex enough to justify something like MS-Access, you can probably get away with just a single flat file. Then the question of editing, deletion, and such become "how do I do xxxx with a file?", which is quite a bit simpler.

  • edit: Take note that unless you're using fixed length fields for records, there's the problem of size variance. If the new data is smaller or larger than the old data during an edit, you need some way of shrinking and growing the file.

    An alternative is to store one record per file, that way it's …

Narue 5,707 Bad Cop Team Colleague

I know how to create a program that sorts names and numbers that are entered from a keyboard, but don't know how to do it whit a file.

Read the file into memory, then sort it as you normally would. While it's possible to sort the file without loading it into memory completely (Google "external sorting"), such methods are quite a bit more complex than in-memory sorting. I also don't believe that your requirements are asking for an external sort.

Narue 5,707 Bad Cop Team Colleague

@jwenting, i would really like to see what that looks like. Can i have a bit of it?

I would wager that it's not open source.