nucleon 114 Posting Pro in Training

^ Non sequitur.

WaltP misread (or did not fully read) the original code, which would simply not accomplish the task. It was the wrong structure, perhaps of the "git-er-done" type, I don't know.

It basically said
* Do all input
* Do all output
whereas the natural structure for the task is
* Open input and output files
* Process files
* Close files

It was certainly not my intent that all of that logic was to be implemented inline. I guess that's what WaltP was talking about. I suppose it does look like I meant it all to be inline, which I didn't really mean. I just meant to indicate a general algorithm that would accomplish the task.

It is left as a (further) exercise to the OP to divide it into appropriate functions. :)

nucleon 114 Posting Pro in Training

OP> How do i get it to parse the ":" and just leave the word sunny

/* This assumes there are no other colons or commas
       before the ones you want. */

    char word[MAX_WORD];
    char *pColon, *pComma;

    pColon = strchr (string, ':');
    if (!pColon) { /* No colon found; handle error. */ }

    pComma = strchr (string, ',');
    if (!pComma) { /* No comma found; handle error. */ }

    if (pComma < pColon) { /* Comma before colon; handle error */ }

    /* Move pColon past the colon. You may also wish to move
        pColon forward past any spaces here. */
    ++pColon;

    strncpy (word, pColon, pComma - pColon);

OP> how would i get it to find that line in a big XML file

If it is always the same line number, just eat lines up to there, then read the line you want. If it's not always on the same line number you will have to search through the text for an identifying pattern, either reading line-by-line or reading the entire text file into memory first. In this situation, with an XML or HTML file, I usually read the entire text into memory, then search that as one big string. Regular expressions are helpful here, but not necessary.

nucleon 114 Posting Pro in Training

Your first attempt was much better. Writing functions is the way to go, as you were doing. Don't follow nucleon's advice.

This is either a joke or he misread your original code. My advice is certainly not to NOT write functions! Of course you should write functions!!! I was just giving a program structure that would actually work.

nucleon 114 Posting Pro in Training

Your structure is wrong. Your main should be something like this:

int main (void) {
    /* Init count of words and count of palindromes to zero */
    /* Open files */
    /* While reading next word does not give EOF */
        /* Increment count of words */
        /* If the word is a palindrome */
           /* Increment count of palindromes */
           /* Ouput to palindrome file */
    /* Show results */
    /* Close files */
}
nucleon 114 Posting Pro in Training

So you are wanting to read a board created by another program. You want to read a screen capture of it?

How many different pieces in mahjong?

If the pieces are different enough and there's not too many, you could probably figure out something simple.

nucleon 114 Posting Pro in Training

What does "written successively in the 15th line" mean?
Do you mean starting at the 15th column?

nucleon 114 Posting Pro in Training

in.ignore() is reading another character and ignoring it. Replace in.ignore(); with continue; to "ignore" the current character in n.

nucleon 114 Posting Pro in Training

Another thing is that string::search() returns string::npos if the search function does not find what it was told to find, and not -1

This is an interesting point. I notice in the standard, clause 21.3 (Class template basic_string), paragraph 6, it does say that: static const size_type npos = -1; size_type is defined a little above that as: typedef typename Allocator::size_type size_type;

nucleon 114 Posting Pro in Training

You could be missing headers. But also, you need to use the c_str() member of a string to open a file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string flight;
    cin >> flight;
    flight = flight + ".txt";
    ofstream myfile;
    myfile.open (flight.c_str());
    myfile << "Hello there.\n";
    myfile.close();
}
nucleon 114 Posting Pro in Training

Resource file:

#include <windows.h>
#include "resource.h"

IDD_CONTROLS_DLG DIALOG DISCARDABLE  0, 0, 160, 230

STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "HSBC Conversion Clock"
FONT 8, "MS Sans Serif"

BEGIN
    LTEXT           "Conversion Time: ",
                    -1,
                    20,  20, 80,   8

    EDITTEXT        IDC_CONVERT_TIME,
                    100,  20, 40,  12,    ES_RIGHT | ES_AUTOHSCROLL

    CHECKBOX        "Between 3/8 - 3/29?",
                    IDC_BETWEEN1,
                    40,  40, 100,  8,     BS_AUTOCHECKBOX

    CHECKBOX        "Between 10/25 - 11/1?"
                    IDC_BETWEEN2,
                    40,  60, 100,  8,     BS_AUTOCHECKBOX

    CONTROL         "Eastern Time",
                    IDC_EASTERN_SELECT,
                    "button",             BS_AUTORADIOBUTTON | WS_GROUP,
                    40, 80, 100, 8

    CONTROL         "UK Time",
                    IDC_UK_SELECT,
                    "button",             BS_AUTORADIOBUTTON,
                    40, 100, 100, 8

    CONTROL         "HK Time",
                    IDC_HK_SELECT,
                    "button",             BS_AUTORADIOBUTTON,
                    40, 120, 100, 8

    LTEXT           "Eastern Time: ",
                    -1,
                    20, 140,  80,  8

    EDITTEXT        IDC_EASTERN_TIME,
                    100, 140,  40, 12,    ES_RIGHT | ES_AUTOHSCROLL

    LTEXT           "UK Time: ",
                    -1,
                    20, 160, 80, 8

    EDITTEXT        IDC_UK_TIME,
                    100, 160, 40, 12,     ES_RIGHT | ES_AUTOHSCROLL

    LTEXT           "HK Time: ",
                    -1,
                    20, 180, 80, 8

    EDITTEXT        IDC_HK_TIME,
                    100, 180, 40, 12,     ES_RIGHT | ES_AUTOHSCROLL

    PUSHBUTTON      "Convert",
                    IDC_CONVERT,
                    25, 200, 30, 15

    PUSHBUTTON      "Quit",
                    IDCANCEL,
                    100, 200, 30, 15
END

Code file:

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "resource.h"


#define GETITEM(item) GetDlgItem(hWndDlg, item)


void convert (HWND hWndDlg) {

    char ConvertTime[8], ETime[8], UKTime[8], HKTime[8];
    char Hour[8], Min[8], AMPM[8];
    int intHour;

    // Gets the user entered time and converts it to usable format
    GetWindowText(GETITEM(IDC_CONVERT_TIME), ConvertTime, 9);
    strncpy(Hour, ConvertTime, 2);
    strncpy(Min, ConvertTime + 3, 2);
    strncpy(AMPM, ConvertTime + 6, 2);
    intHour = atoi(Hour);

    if (strchr(ConvertTime, 'A') == NULL ||
        strchr(ConvertTime, 'P') == NULL ||
        strchr(ConvertTime, 'a') == NULL …
nucleon 114 Posting Pro in Training

Try changing the relevant part of the rc file to this:

CONTROL "Eastern Time", IDC_EASTERN_SELECT,
        "button", BS_AUTORADIOBUTTON | WS_GROUP,
        40, 80, 100, 8

    CONTROL "UK Time", IDC_UK_SELECT,
        "button", BS_AUTORADIOBUTTON,
        40, 100, 100, 8

    CONTROL "HK Time", IDC_HK_SELECT,
        "button", BS_AUTORADIOBUTTON,
        40, 120, 100, 8

Set the initial radio button while handling WM_INITDIALOG:

// Init radio button group.
    CheckRadioButton (hWndDlg,
                      // First and last of consecutive list
                      // of radio button id's.
                      IDC_EASTERN_SELECT, IDC_HK_SELECT,
                      // Id to set; all others are reset.
                      IDC_EASTERN_SELECT);
nucleon 114 Posting Pro in Training

Your stack trace clearly shows the string allocator blowing up. But how is that possible? Sadly anything is possible with undefined behavior. You could zip your source and attach it.

nucleon 114 Posting Pro in Training

Excellent info, Narue and vmanes!
(I'm beginning to like being proved wrong.)
And wikipedia does have some decent info, especially the complexity tables.

nucleon 114 Posting Pro in Training

Good points, Narue, as usual. It's just all that clearly repetitive code. It isn't really spaghetti code (that would presumably require goto's), but it somehow feels like it. As you say, no design.

nucleon 114 Posting Pro in Training

I completely misread your algorithm. I didn't even realize it was using two arrays. That's an interesting trick. But your revised code is slightly better, so some good came out of it!

I'm getting some truly horrible numbers (for average sum of elements 0 to 4, i.e., the "front" of the array) from shuffleBad in this revised code:

/* Example run:
ShuffleBad:
  Front: 2.162890
  Back:  2.518120
ShuffleGood:
  Front: 2.501900
  Back:  2.500930
*/

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

#define REPETITIONS  100000
#define ARRAY_SIZE   52
#define TEST_NUMS    5

typedef void (* shuffle_func ) (int[], int);

/* Always picks rnd int from 0 to size - 1 (inclusive) */
void shuffleBad (int deck[], int size) {
    int i;
    for (i = 0; i < size; ++i) {
        int r = rand() % size;
        int t = deck[i]; deck[i] = deck[r]; deck[r] = t;
    }
}

/* Picks rnd int from decreasing range */
void shuffleGood (int deck[], int size) {
    int i;
    for (i = size - 1; i > 0; --i) {
        int r = rand() % (i + 1);
        int t = deck[i]; deck[i] = deck[r]; deck[r] = t;
    }
}

/* Load first half of deck with 0, second half with 1. */
void initDeck (int deck[], int size) {
    int i;
    for (i = 0; i < size / 2; ++i)     deck[i] = 0;
    for (i = size / 2; i < size; ++i)  deck[i] = 1;
}

int sumFirstN (int deck[], int n) {
    int …
nucleon 114 Posting Pro in Training

I believe you do in fact catch the exception as it is "going on". And since you can catch different exception types, you can tell which is which.

Here's a simplified version of loadFile. More ... stringy. Less ... errory.

#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>

std::string loadFile ( const char* path )
    throw (std::runtime_error) {
    std::string fileContent;
    std::ifstream fin ( path );
    if ( !fin ) throw std::runtime_error ( "Couldn't open file" );
    std::string line;
    while ( getline ( fin, line )) {
        fileContent += line;
        fileContent += '\n';
    }
    return fileContent;
}

int main ( int argc, char** argv ) {
    std::string file = loadFile ( "myfile.txt" );
    std::cout << file;
}
nucleon 114 Posting Pro in Training

Code is not supposed to look like that. A single function should not span page after page. You've managed to produce structured spaghetti code, with meatballs. (I don't even know what that means.) :)

Divide it up into more pieces. More objects, or at least more functions. If something seems repetitive, if it's copied over and over with little change, break it out as a function and parameterize the changing stuff.

Checking the legality of moves and applying them to the board should be fairly simple once the other stuff is cleaned up.

nucleon 114 Posting Pro in Training

By jove, he's right! Below is a test program for the two shuffles.

StuXYZ: Your for loop condition should be i > 1, since when it equals one it always "switches" element zero with element zero.

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

#define REPETITIONS 1000
#define ARRAY_SIZE    52
#define TEST_NUMS     10

typedef void (*shuf_func) (int[], int);

void shuffle1 ( int deck[], int size ) {
    int i;
    for (i = 0; i < size; ++i) {
        int r = rand() % size;
        int t = deck[i]; deck[i] = deck[r]; deck[r] = t;
    }
}

void shuffle2 ( int deck[], int size ) {
    int i;
    for (i = size - 1; i > 0; --i) {
        int r = rand() % (i + 1);
        int t = deck[i]; deck[i] = deck[r]; deck[r] = t;
    }
}

void init ( int deck[], int size ) {
    int i;
    for (i = 0; i < size / 2; ++i)     deck[i] = 0;
    for (i = size / 2; i < size; ++i)  deck[i] = 1;
}

int test ( int deck[], int size ) {
    int i, n = 0;
    for (i = 0; i < size; ++i) n += deck[i];
    return n;
}

void testShuffle (shuf_func shuffle) {
    int i, total = 0;
    int deck[ARRAY_SIZE];
    for (i = 0; i < REPETITIONS; ++i) {
        init ( deck, ARRAY_SIZE );
        shuffle ( deck, ARRAY_SIZE );
        total += test ( deck, TEST_NUMS );
    }
    printf ( "%f\n", (double)total / (REPETITIONS * TEST_NUMS));
}

int main() {
    srand ( time ( 0 ));

    testShuffle ( shuffle1 );
    testShuffle ( shuffle2 );
}
nucleon 114 Posting Pro in Training

Four bad sorts:
bubble sort
insertion sort
selection sort
shell sort

nucleon 114 Posting Pro in Training

You can't ensure that this code will move every element at least once

Good point. I don't know what I was thinking. An element should be allowed to stay in the same place, otherwise it is certainly not a random permutation.

nucleon 114 Posting Pro in Training

Here's a simple shuffle that ensures every element is moved at least once. Note the loop only needs 13 reps for 13 numbers.

const int MAX = 13;
int a[MAX];
for (int i = 0; i < MAX; ++i) a[i] = i;
for (int i = 0; i < MAX; ++i) {
    int r = rand() % MAX;
    int t = a[i]; a[i] = a[r]; a[r] = t;
}
nucleon 114 Posting Pro in Training

I suppose the canonical example is the example at the bottom of CWnd::OnCtlColor on MSDN.

nucleon 114 Posting Pro in Training

This is old school indeed:

int set_keysig (s, ks, init)
  char s[];
  struct KEYSTR *ks;
  int init;
{
   /* function body */
}

Should be updated to:

int set_keysig (char s[], struct KEYSTR *ks, int init)
{
   /* function body */
}

Other than that (and the missing stdio.h header and the fact that you're not returning anything), your posted code has no errors. The lowercasing code should set all but the first character of each word to lowercase. (This is assuming that the "working code" really does "work" ... which seems unlikely given your results.)

Aia commented: Thank you for correcting me. +15
nucleon 114 Posting Pro in Training

> You have to use a little pointer arithmetic too (as
> opposed to plain old indexing).

Just to correct this. You don't have to use pointer arithmetic, but you do have to use the addresses of elements as opposed to just their values. So either of these forms should do:

strncpy (to, line + pos, size);  // pointer arithmetic
strncpy (to, &line[pos], size);  // index and address-of
nucleon 114 Posting Pro in Training

sum must be initialized to zero.
You don't need the variable add.

nucleon 114 Posting Pro in Training

To set up a handful of records, perhaps for a little hard-coded testing, you can, of course, do this:

// Initializing first 3 fields of first 2 records
    singleIMEI a[30] = {{"00","01","02"},
                        {"10","11","12"}};
nucleon 114 Posting Pro in Training

And you haven't said what the format of the line is. There are two common possibilities: a fixed-length format and a delimited format.

A fixed-length is like this:

name0---addr0---phone0---info0-----pay0---
name1---addr1---phone1---info1-----pay1---
name2---addr2---phone2---info2-----pay2---

(As long as you're only accessing it sequentially, the last field could actually be variable length since the end-of-line character acts as a delimiter.)

You can read this format by reading in the first how-ever-many characters, then the next how-ever-many characters, etc. That could be done with just strncpy and strcpy (which makes me suspect this format). You have to use a little pointer arithmetic too (as opposed to plain old indexing).


On the other hand, a delimited format is like this:

name:addr:phone:carinfo:payment

And is processed by finding the colons, one at a time, extracting the substrings as you go.

nucleon 114 Posting Pro in Training

What are you doing with words like a, the, on, and, it, etc. They would seem to contribute an inordinate amount to the score and yet nothing to a sentence's "importance". It's possible they just average out, I guess. Or maybe you could have an ignore list of the so-called functional words of English (articles, conjunctions, prepositions, pronouns, etc).

Keeping in mind ArkM's suggestion to use a map<string,int> to accumulate the word frequencies, here's an algorithm:

Read in sentence file

For each sentence
  For each word
    If not on ignore list  //if you need this
      Increment frequency of that word

For each sentence
  Set sentence weight to the sum of its word weights

Sort sentences by sentence weights.

Store/Display top N sentences.
nucleon 114 Posting Pro in Training

regexes can be worthwhile.

nucleon 114 Posting Pro in Training

Oops. I meant here.
At any rate, I've already repented. It's probably best to use string::npos. I've been relying on that online C++ reference a little too much. I like the level of detail but I guess when it's implementation detail, it's just "informative" (as the standard would say).

nucleon 114 Posting Pro in Training

its a poorly written program.
...
line.find() doesn't return -1, it returns string::npos.

Yeah, it's a pretty rickety structure, I must admit. :( I suppose that's just another reason not to post "solutions" since the kind of thing you whip up in five minutes is likely to be error-prone and limited.

But it is my understanding that string::npos does in fact equal -1. I get my info from here. Also it works well and without warning on gcc and vc++ compilers.

nucleon 114 Posting Pro in Training

Clockowl: Your program will still fail if a line is too long since only part of the line will have been read, leaving the rest of that line to be read as the next line. It's probably best to forgo strtok altogether and just use C++ strings and member functions like find_first_of and substr. (Also note that the version presented below definitely needs the colon at the end of the line, as in the OP's original data file.)

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main() {
    ifstream ins ("Line.txt");
    string line;
    vector<string> fields;

    while (getline (ins, line)) {
        cout << line << '\n';

        size_t lastPos = 0;
        while (true) {
            size_t pos = line.find_first_of (":", lastPos);
            if (pos == -1) break;
            fields.push_back (line.substr (lastPos, pos - lastPos));
            lastPos = pos + 1;
        }

        for (int i = 0; i < fields.size(); ++i)
            cout << fields[i] << '\n';
        fields.clear();
    }
}
nucleon 114 Posting Pro in Training

You kids and your string toking!

Firstly, if your filename is actually "lines.txt" (as you say at the bottom of your post) then that's probably the filename you should use in your program. :)

And you should test the stream like this: while (ins >> line)

nucleon 114 Posting Pro in Training

> How else can they be different?
Yep, they must be the same function.

It works if you pick a specific copy like this: mycar.racer::cruise(50); or this mycar.tank::cruise(50); But "diamond inheritance" looks like something to avoid in general. Seems strange that the language wasn't designed to include only one copy in such a case.

nucleon 114 Posting Pro in Training

I find it useful on occasion to place a prototype in a function. (pssssssssssss)

nucleon 114 Posting Pro in Training

How much of your OS is finished? If you're asking about the GUI you must at least have finished the kernel and a command-line interface. Will your OS have virtual memory? Multitasking? Obviously it must have a file system. Are you writing the device drivers yourself, too? Quite a project (unless you steal most of your code from linux). The GUI is the least of your worries.

nucleon 114 Posting Pro in Training

I'm not a socket-head, but since no one has helped you yet, I'll point out a couple of things. If you want help from others, I suggest you give more detail about what it is doing wrong.

This method of turning a number into a string will only work if the number is between 0 and 9:

op[0] = count + 48;
    op[1] = '\0';

So if your file has more than 9 lines, you're in trouble!
Try something like this:

if (snprintf (op, sizeof(op), "%d", count) >= sizeof(op)) {
        perror("overflowed op");
        exit (-1);
    }

In general, everywhere you use perror() you probably want to exit right after it.

Also, op is a very strange name that gives no clue as to it's purpose. How about calling it strNLines and count could be nLines.

And your code-layout is very bad! Do not mix spaces and tabs. I always just use spaces since that will display properly anywhere, such as when posted to a website.

nucleon 114 Posting Pro in Training

It would also be nice if it worked. Did you test it fully? Try entering an incorrect password followed by the correct password.

Also, terminate and terminator are confusing names. How about triesUsername and triesPassword ?

nucleon 114 Posting Pro in Training

You're defining your array with a size of zero. (ARRAYSIZE is 0.)

And even if you fix that, your code often refers to listitem, which is outside the array bounds.

nucleon 114 Posting Pro in Training

What exactly is wordCount counting? Aren't you passing it a single word?

nucleon 114 Posting Pro in Training

Try something like GetTextExtentPoint32 or one of it's cousins.

nucleon 114 Posting Pro in Training

typedef struct node{ int *datapointer; struct node *next; } NODE; You probably want int *datapointer to be int data , because of how you are using it here (you are trying to assign an integer to a pointer): temp -> datapointer = num; Otherwise you'd have to allocate space for the integer you want to assign, assign the integer to that allocated space, and store the pointer to the space in datapointer. Seems overly complicated just for an integer!

nucleon 114 Posting Pro in Training

In equal(), declare L1 and L2 as NODE*, not node.
C does not generally support bool (use int).
TRUE and FALSE need to be declared, or just use 1 and 0.
(Or perhaps your version of C supports bool, in which case you mean true and false, not TRUE and FALSE.)
You spell p_cmp_func as p_cmp_f in the return.
NEXT is not defined anywhere but is used in the return.

By the way, it is customary to mark a thread as solved when it is solved.

nucleon 114 Posting Pro in Training

You shouldn't really "BUMP" a post. At least pretend to ask another question!

regex is something you can look up yourself, but it is not necessary for your problem. Here's an example of parsing a simple config file:

/* File config.txt:
num = 123
str = hello
flt = 12.2
*/

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

struct Config {
    int    num;
    string str;
    double flt;
};

void loadConfig(Config& config) {
    ifstream fin("config.txt");
    string line;
    while (getline(fin, line)) {
        istringstream sin(line.substr(line.find("=") + 1));
        if (line.find("num") != -1)
            sin >> config.num;
        else if (line.find("str") != -1)
            sin >> config.str;
        else if (line.find("flt") != -1)
            sin >> config.flt;
    }
}

int main() {
    Config config;
    loadConfig(config);
    cout << config.num << '\n';
    cout << config.str << '\n';
    cout << config.flt << '\n';
}
nucleon 114 Posting Pro in Training

You need to use the prefix form of ++ and --. So: return( add( ++n, --m ) ) ;

nucleon 114 Posting Pro in Training

In line 20 of your code you are returning an integer (the second operand of the comma operator), so the compiler complains that it cannot turn an int into your actual return type which is a vector.

Replace lines 18-21 with this:

StringIntVector vRet;
    for (iter=freq.begin(); iter != freq.end(); iter++)
        vRet.push_back(*iter);
    return vRet;

And isnotpuct should probably be called isnotpunct (I didn't know what puct was, but I know what punct is).

nucleon 114 Posting Pro in Training

Remove the additional asterisk.
Declare table like this: Object3D* table;

nucleon 114 Posting Pro in Training

What is _word_list ?
What is isnotpuct ?
What is wordCount() ?

nucleon 114 Posting Pro in Training

Does this line work if you type it into a console in the proper directory? CC -c driver.cpp When I used unix I only used C. Is CC (as opposed to cc) the C++ compiler?

nucleon 114 Posting Pro in Training

Good point !