Tom Gunn 1,164 Practically a Master Poster

Then it doesn't gather numbers correctly but stores the entire string

That's what you tell it to do with getline(cin,problems) . I can help you fix it by taking the entire line and parsing it, but I need you to describe the format of the problemset. Just showing your code isn't enough.

Tom Gunn 1,164 Practically a Master Poster

It already prompts for enter again. I'm going to guess that the problem is with extra stuff being stuck in the stream when you prompt again. You should clear it out. A good way to do that is to use strings and getline so that there isn't ever any extra stuff. Here's your code with that change, but I removed the timer parts because I don't have your header:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    bool quit = false;
    string line;

    while(! quit)
    {
        cout<<"hit enter when you want to stop timer\n";
        if(getline(cin, line) && line.empty())
        {
            cout<<"enter yes if you want to find out time differences for more times\n";
            if(getline(cin, line) && line == "yes")
            {
                cout<<"from yes\n";
            }
            else
            {
                cout<<"from no\n";
                quit=false;
                break;
            }
        }
    }
    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

This page is kind of Linux-centric, but the printf info should be standard.

Tom Gunn 1,164 Practically a Master Poster

What I had been using till now was "rusted, naff,useless" code.

There's nothing wrong with writing code on an old compiler. You gotta do what you gotta do, and what you gotta do isn't ever ideal. ;) It's easy for some armchair critic to complain, but you're the one who has to get the job done by any means necessary.

If anyone could help me and provide me with link to the better tutorials on Standard and modern C++, I would be highly grateful.

These two books will help.

From my information, conio.h is not in use anymore.

conio.h is used a lot. There's not a standard way to do the stuff conio.h does either. Clearing the screen, changing text color, getting a key press without typing Enter, standard C++ doesn't do any of it the same way, and the standard analogs are not as useful. If you need something from conio.h, no matter how you go about it you'll get yelled at by somebody that it isn't portable, and your code is wrong, and standard C++ is GOD, and you're stupid for not writing code exactly like them, and whatever else those guys whine about. ;)

I say you should learn how to use everything, portable or not, standard or not, and then choose the best of them for what you need to do. Being standard and portable is a great goal, but to get anything substantial done you have to compromise somewhere.

siddhant3s commented: Some of the Baddest advices I ever heard. -2
William Hemsworth commented: Agree with siddhant3s. -2
Tom Gunn 1,164 Practically a Master Poster

Ok, that's understandable. You can still do the same thing with a temporary array and an initializer, then a loop to assign the temporary array to the array field:

#include <iostream.h>

class suitcase
{
    long double amount[20];
public:
    suitcase();

    void print()
    {
        int i;

        for (i = 0; i < 20; i++)
            cout << amount[i] << '\n';
    }
};

suitcase::suitcase()
{
    long double temp[20] =
    {
    0.25,1.0,10.0,100.0,250.0,500.0,1000.0,5000.0,10000.0,50000.0,
        100000.0,200000.0,300000.0,400000.0,500000.0,1000000.0,
        2500000.0,5000000.0,7500000.0,10000000.0
    };
    int x;

    for (x = 0; x < 20; ++x)
        amount[x] = temp[x];
}

int main()
{
    suitcase s1;
    s1.print();
    return 0;
}
Tom Gunn 1,164 Practically a Master Poster

"cout" doesn't support any specific formatting.

cout supports a lot of formatting options, and you can add more. It is a very flexible design, much more flexible than printf. But the design is very verbose and convoluted compared to printf.

You can use printf defined under stdio. Use a corresponding qualifier.

I agree. For most of the formatting jobs that printf can do, it is shorter and probably faster that cout. Which makes more sense here when printing fixed format with no precision?

#include <iostream>
#include <iomanip>
#include <cstdio>

using namespace std;

int main()
{
    long double value = 100000000.0;

    // chained modifiers on cout
    cout << fixed << setprecision(0) << value << '\n';

    // printf with a format string
    printf("%.0f\n", value);
}

The cout line is a little over twice as long, and it is not as obvious what the output will look like by skimming the code. I think formatting macros embedded in an output string are easier to figure out, but not having to type all of that extra junk is a big win.

Tom Gunn 1,164 Practically a Master Poster

If you switch to standard C++ instead of an older version, you can use the STL vector class and initialize it with an array. The Boost library has a way of doing it directly to a vector without the array, and C++0x will add that into the language itself. But this works without Boost or waiting for the next standard to get implemented. It's a little shorter:

#include <iostream>
#include <vector>

using namespace std;

class suitcase
{
    vector<long double> amount;
public:
    suitcase();

    void print()
    {
        for (int i = 0; i < amount.size(); i++)
            cout << amount[i] << '\n';
    }
};

suitcase::suitcase()
{
    long double temp[20] =
    {
        0.25,1.0,10.0,100.0,250.0,500.0,1000.0,5000.0,10000.0,50000.0,
        100000.0,200000.0,300000.0,400000.0,500000.0,1000000.0,
        2500000.0,5000000.0,7500000.0,10000000.0
    };

    amount = vector<long double>(temp, temp + 20);
}

int main()
{
    suitcase s1;
    s1.print();
}
Tom Gunn 1,164 Practically a Master Poster

If you want to treat each row as an individual object, a 2D array is easier to work with and visualize. A good way to swap rows is a second array of pointers that point into the matrix. You swap those pointers for different sorting options and the matrix doesn't ever change:

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

#define XSZ 3
#define YSZ 12

void PrintMatrix(int **pmat, int xsz, int ysz);
void ReverseMatrix(int **pmat, int sz);

int main()
{
    int matrix[][YSZ] =
    {
        0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11,
        12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
        24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35
    };
    int *pmat[XSZ];
    int x;

    for (x = 0; x < XSZ; ++x) pmat[x] = matrix[x];

    PrintMatrix(pmat, XSZ, YSZ);
    printf("\n");
    ReverseMatrix(pmat, XSZ);
    PrintMatrix(pmat, XSZ, YSZ);

    return EXIT_SUCCESS;
}

void PrintMatrix(int **pmat, int xsz, int ysz)
{
    int x, y;

    for (x = 0; x < xsz; ++x)
    {
        for (y = 0; y < ysz; ++y)
        {
            printf("%-3d", pmat[x][y]);
        }

        printf("\n");
    }
}

void ReverseMatrix(int **pmat, int sz)
{
    int x, y;

    for (x = 0, y = sz - 1; x < y; ++x, --y)
    {
        int *temp = pmat[x];
        pmat[x] = pmat[y];
        pmat[y] = temp;
    }
}

It also works with a 1D array like the one in your code. As long as you work with pmat instead of matrix, the only difference is how pmat is constructed:

jephthah commented: if you're gonna spoonfeed entire solutions, you should at least have the decency to FedEx a DVD-ROM and spiral bound instruction manual. -2
csurfer commented: Your "Good" intentions are leading the OP in a "Wrong" way !!! +0
Tom Gunn 1,164 Practically a Master Poster

i couldn't understand the "." format...

It's one of the new features to C. You can initialize struct members by name instead of by position:

struct test
{
    int first;
    int second;
    int third;
};

struct test a = {0, 0, 1}; /* Old way */
struct test b = {.first=0, .second=0, .third=1}; /* New way */

It's useful because you don't have to initialize every member before the one you want to initialize. 0 is the default, so if I wanted to only initialize third, the old way is still the same but the new way is easier:

struct test b = {.third=1}; /* Same thing */

Designated initializers are a C99 feature. To use them you need to have a compiler that allows C99.

Tom Gunn 1,164 Practically a Master Poster

Now the problem is this snippet works fine but the fact i want the section of the file to be read not the entire file.Thats the reason am using '*' deliminater in getline(ifs,line,'*') in my code.

Oh, I get it now. I thought that the '*' was on multiple lines as a wildcard or something. To stop reading the file at '*', check to see if '*' was found and removed:

while (getline(ifs, line))
{
    // locate the first occurrence of '*' in the line
    // use string::npos if '*' is not found
    string::size_type end = line.find_first_of('*');
    // extract a substring up to the found '*'
    // end==string::npos extracts the whole line
    string command = line.substr(0, end);

    cout << command <<'\n';
    system(command.c_str());

    // stop reading the file if '*' was found
    if (end != string::npos) break;
}
Tom Gunn 1,164 Practically a Master Poster

If the replacement lines aren't exactly the same length as the lines being replaced, you need to rewrite the whole file. If they are the same length you can just overwrite the first ten lines.

Tom Gunn 1,164 Practically a Master Poster

You created a windows application project and don't have a WinMain function. WinMain is the entry point for windows applications. If you're writing a program that uses main instead of WinMain, change the project type to a console application. If you really do want a windows application, there has to be a WinMain function somewhere in your .cpp files.

Tom Gunn 1,164 Practically a Master Poster

I'm sorry, I wasn't clear enough. The default delimiter for getline is '\n'. That is what you want. After you get the line you need to parse the parts you want to keep. There are two steps: read a line and extract a substring from the line:

while (getline(ifs, line))
{
    string::size_type end = line.find_first_of('*');
    string command = line.substr(0, end);

    cout << command <<'\n';
    system(command.c_str());
}
Tom Gunn 1,164 Practically a Master Poster

You don't need to store them all at one. Instead, loop it:

while (getline(ifs, line))
{
    // do your thing
}

When there aren't any more lines, getline will return a condition that stops the loop.

Tom Gunn 1,164 Practically a Master Poster

SetConsoleTextAttribute can change the foreground and background:

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

using namespace std;

HANDLE SetColor(
                HANDLE console, 
                int fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
                int bg = 0)
{
    if (console == NULL)
        console = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleTextAttribute(console, fg | bg);

    return console;
}

int main()
{
    HANDLE console = SetColor(NULL, FOREGROUND_RED, BACKGROUND_GREEN);

    cout << "Hello world!\n";
    SetColor(console);
    cout << "All done.\n";
}

and I'd also be glad to know another way to clear the screen

Here is a windows way:

void clear_screen()
{
    DWORD n, size;
    COORD coord = {0};
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

    GetConsoleScreenBufferInfo(h, &csbi);
    size = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(h, TEXT(' '), size, coord, &n);
    GetConsoleScreenBufferInfo(h, &csbi);
    FillConsoleOutputAttribute(h, csbi.wAttributes, size, coord, &n);
    SetConsoleCursorPosition(h, coord);
}
Tom Gunn 1,164 Practically a Master Poster

But as for scope, if i make an object on the heap, i can access it from anywhere right? It's like a global variable right?

Heap memory is accessed through pointers. It's the pointer that has to follow scope rules, not the heap object. If you have a global pointer and point it to that address, it's like a global variable. If you have a local pointer and point it to that address, it's not like a global variable.

Tom Gunn 1,164 Practically a Master Poster

I thought you were from USA, what nationality are you?

Military service in the US hasn't always been voluntary. The draft only stopped around 1980.

Tom Gunn 1,164 Practically a Master Poster

A function pointer is still a pointer. If you set it to NULL or 0 it is a null pointer and then the test is easy:

for (int x = 0; x < nFeats; ++x)
{
    if (feats[x] != NULL) (*feats[x])();
}
Tom Gunn 1,164 Practically a Master Poster

You could also use player2--

You could, but to get the same behavior it has to be in a loop:

for (int x = 0; x < hit; ++x) --player2;

-- only decrements a variable by 1, it is the same as player2 = player2 - 1 or player2 -= 1 .

Tom Gunn 1,164 Practically a Master Poster

I'm have a small confusion, and i need a little clarification; when you make something on the heap, like this:

int *somePointer = NULL;
somePointer = new int;

an int is created on the heap right?

This would be the equivalent of doing something like...:

int x;

...directly on the heap, right?

Right. But don't forget that heap memory needs to be deleted when you are done with it:

int *somePointer = new int;

*somePointer = GetInt();
cout << *somePointer << '\n';

delete somePointer;

Also, what are the scope limitations of the heap?

Scope limitations?

Tom Gunn 1,164 Practically a Master Poster

I don't understand what the 0 and -5 thing is with that code, but your player's hit points don't ever get subtracted from. If you do player2-hit; , it doesn't change player2. You need to do player2=player2-hit; to save the changes. Or player2-=hit is a little shorter and does the same thing.

I'd also move the check for player1 and player2 being less than 0 to outside the attack2 if statement. But because you print the hitpoints before checking for a game over, it will still print negative values. You can fix that by only printing positive hitpoints. If the hitpoints are below 0, print 0.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;

int positive(int value)
{
    return value >= 0 ? value : 0;
}

int main ()
{
    srand(time(0));
    int player1 = 100;
    int player2 = 100;
    char player1Name;
    char player2Name;
    int PlayerTurn(1);
    int Attack;
    bool GameOver(false);
    bool GameWin(false);
    do {
        cout << "it's player" << PlayerTurn << "'s turn" << "do you want to attack with a high risk or a low risk attack? low risk = type1 high risk = type2" << endl;
        cout << "Attck with type >>";
        cin >> Attack;
        if(Attack == 1) {
            double hit = rand() % 31 + 10;
            if(PlayerTurn == 1){
                player2-=hit;
                cout << "you took " << hit << " points from player2" << endl;
                cout << "\nplayer2 has " << positive(player2) << " points left\n" << endl;
            }
            else {
                player1-=hit;
                cout …
Tom Gunn 1,164 Practically a Master Poster

Your program doesn't ignore punctuation marks, a great programmer as you would certainly have seen that, not?

I'm not a great programmer by any measure, but I did say that the definition of 'word' is important in my first post:

For a loose definition of 'word', you can use cin:

string word;

while (cin >> word)
{
      cout << word << '\n';
}

For a stronger definition of 'word', you should do more parsing than just looking for spaces. Punctuation and stuff like that wouldn't be a part of the word, right?

Salem jumped me about giving away code, so I didn't give an example of the stronger definition. Blame him. ;)

Tom Gunn 1,164 Practically a Master Poster

And, with your otherwise excellent solution, you have to terminate input with Ctrl+Z instead of just <Enter>

The problem was to allow the user to enter a paragraph. I bet there will be more than one line, and to handle multiple lines with getline you need to terminate input with something besides <Enter>.

>They add unnecessary complexity?
Oh stop kidding......
They are simplifying the program not making it more complex. Your example won't work if you intend to write a function to count the number of words in a given string.

Who's kidding? You're adding more complexity by making the code 'function ready' when Alicito's code does everything in main. Besides, if you want to write a function you can pass an istream and use the same short code without hurting flexiblity. It works with stringstreams and fstreams too:

#include <iostream>
#include <string>

using namespace std;

unsigned long CountWords(istream& stream)
{
    unsigned long count = 0;
    string str;

    while (stream >> str) ++count;

    return count;
}

int main()
{
    cout << CountWords(cin) << '\n';
}

Ancient Dragon's complaint makes more sense, but only if you're reading one line interactively.

Tom Gunn 1,164 Practically a Master Poster

Why not use stringstreams?

They add unnecessary complexity?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;

    while (cin >> str) count++;
    
    cout << count << '\n';
}
Tom Gunn 1,164 Practically a Master Poster

For a loose definition of 'word', you can use cin:

string word;

while (cin >> word)
{
    cout << word << '\n';
}

For a stronger definition of 'word', you should do more parsing than just looking for spaces. Punctuation and stuff like that wouldn't be a part of the word, right?

edit
By the way, isspace checks for all space characters: {' ', '\t', '\r', '\n', '\v', '\f'}. Your program should work with tabs too, but you don't take multiple space characters between words into account, so the word count is wrong.

Tom Gunn 1,164 Practically a Master Poster

Some of the ads have the wrong z-index. The Verizon Wireless one is an example because it always stays on top of the forum and control panel dropdown menus. I can't get to some of the links that way and have to reload the page to get a different ad.

Loading the ads is slow too, but I don't know if there's anything that can be done about that.

Tom Gunn 1,164 Practically a Master Poster

If you just want a reference, "C: A Reference Manual" is the best. A good beginner book is "C Primer Plus".

jephthah commented: C: A Reference Manual is extremely well reviewed. i'll have to check that out +11
Tom Gunn 1,164 Practically a Master Poster

One thing you could try:

long long num = 123456789123[B]ll[/B];

Just a guess though.

ll looks too much like 11. LL is easier to see as a literal suffix.

Tom Gunn 1,164 Practically a Master Poster

There's a line between "help" and "spoon-feeding the complete answer".

If I cross the line then one of the moderators will let me know, but I'll keep those links in mind when I post.

jephthah commented: or maybe the users will. dont be such a smartass -2
Tom Gunn 1,164 Practically a Master Poster

With that solution increase your buffer size slightly

It should be no less than the largest expected line length. I picked 20 because none of the lines in the example file were longer than that.

don't forget your fclose()

You don't need to fclose() if the program ends. When the program ends normally, all open files are flushed and closed.

Also note "rt" on the fopen() if you need your line terminator translation.

"r" is already text mode where whatever line terminator combination is used on the OS, it becomes '\n' inside your program. "rb" is binary mode, and those translations aren't made. "rt" isn't portable.

Tom Gunn 1,164 Practically a Master Poster

Use recursion:

#include <stdio.h>

void PrintFileBackward(FILE *fp);

int main()
{
    FILE *fp = fopen("test.dat", "r");
    PrintFileBackward(fp);
    return 0;
}

void PrintFileBackward(FILE *fp)
{
    char s[20];
    if (!fgets(s, 20, fp)) return;
    PrintFileBackward(fp);
    fputs(s, stdout);
}

Each time you call PrintFileBackward, the next line is read from the file. Then when the functions are rolling back up the stack, each line is printed. But because lines are printed from the inside out in the opposite order that they were read, they get printed in reverse.

Cool, huh?