Narue 5,707 Bad Cop Team Colleague

Abstraction means Giving only essential things and hiding unnecessary details.

Implementation details are often hidden away behind a more intuitive interface in abstraction, but that's not required. Abstraction is the process of matching the representation of data or algorithms to their meaning within a program. It's a method of implementing "code for the application, not the computer".

An example of abstraction is std::map<A,B>. We only care about uniquely mapping A to B and being able to perform fast lookups of B based on A. There's really no reason to know that std::map is implemented as a balanced search tree, and we certainly don't want to worry about managing the details of a search tree when we really just want a mapping.

The std::map abstraction gives us the ability to write what we meant in terms of the application rather than lower level junk that makes the computer happy and just obscures what the application is really doing. This is abstraction.

Encapsulation means binding the data members and methods together in a capsule form to avoid accidental changes to data from external users.

Encapsulation is the bundling of related algorithms and data. It's possible (and not entirely uncommon) to use encapsulation without any kind of data hiding:

struct point {
    int x;
    int y;

    point(int x, int y);
};

struct line {
    point a;
    point b;

    line(point a, point b);
    double distance() const;
};

This bundling makes for convenient interfaces as well as simplifies the task of …

Narue 5,707 Bad Cop Team Colleague

Nice work. But generally people want to KEEP single spaces and remove more than double spaces.

http://www.daniweb.com/software-development/cpp/threads/106452/518972#post518972

Also look into writing a trim function.


http://www.daniweb.com/software-development/cpp/threads/155472/729101#post729101

Maybe we can steal Apple's catch phrase and modify it for C++: "There's an algorithm for that".

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

using namespace std;

struct whitespace {
    bool operator()(char a, char b)
    {
        return isspace(a) && isspace(b);
    }
};

int main()
{
    string s("here Is    A   String With White  \n  Space");

    cout << "Before: '" << s << "'\n";
    s.erase(unique(s.begin(), s.end(), whitespace()), s.end());
    cout << "After:  '" << s << "'\n";
}
mrnutty commented: Oh why are thou so witty +13
Narue 5,707 Bad Cop Team Colleague

whether or not you use command-line arguments for this program, you should get in the habit of defining your main() as:

Why define parameters that aren't used? You're lying to readers of your code by saying that you'll use command line arguments and then not using them. Not only does this reduce readability, it might also introduce warnings about unused parameters. If you don't use command line arguments, define make as taking no parameters:

int main(void)
{
    ...
}

As for the original code, I can't help but offer a full review:

Best Practice

>#include<conio.h>
Note that <conio.h> is not a standard header, many compilers will not support it, and those that do will not all support the same things in the same ways. For example, Borland compilers support textcolor() while Microsoft compilers do not, yet both support getch(). I won't say not to use <conio.h> because there are legitimate uses (such as kbhit() and getch() for reading raw input), but most of the time I see stupid crap like this:

#include <conio.h>

int main(void)
{
    clrscr(); /* 1) Either stupid or anti-social */

    ...

    getch(); /* 2) Unnecessary destruction of code portability */

    return 0;
}
  1. Clearing the screen at the start of the program does one of two things:
    • Nothing: If you run the program from an IDE or other application where the console window is created exclusively for your program, there won't be any previous output to clear.
    • Clear previous program output: …
sergent commented: Looks like a lot of hard work!! +3
Narue 5,707 Bad Cop Team Colleague

Are you asking a question, or just showing off your substandard programming abilities?

Narue 5,707 Bad Cop Team Colleague

I don't see whats wrong with good ol' C++.

One example, two words: string processing.

abelLazm commented: :) +0
Narue 5,707 Bad Cop Team Colleague

Duplicate threads merged.

Narue 5,707 Bad Cop Team Colleague

Can you get any less specific? :icon_rolleyes:

Tellalca commented: :)))) +0
Narue 5,707 Bad Cop Team Colleague

Formatted input (with the >> operator) and unformatted input (getline is an example) don't play well together. It's a subtle combination of features that work together to give you this bug:

  • Requests only block (wait for you to type) if the stream is empty
  • Operator >> first discards leading whitespace
  • Operator >> stops reading when it sees whitespace and doesn't discard it
  • getline() does not discard leading whitespace
  • getline() stops reading when it sees '\n' and does discard it
  • '\n' counts as whitespace, so operator >> stops on it

So what happens is you type the GPA (say 123.45) and hit enter to send input from the command line to cin. cin now contains the string "123.45\n" because the enter key is recognized as the '\n' character.

Operator >> successfully extracts 123.45 and places it in Gpa, but stops when it sees '\n' and leaves that '\n' in the stream for subsequent input requests.

Now getline() is called and sees '\n'. It doesn't block for input because there's already something in the stream, and that something causes getline() to terminate immediately and successfully with an empty string being stored in Name.

That's the "why" of your problem. Now how do you fix it? The best way is not to mix formatted and unformatted input, but if you're new to C++ that might be too much to ask. A simple solution is removing the newline prior to calling getline (an operation we often call flushing …

Muhammad Anas commented: thankyou very much for such a detailed and easy to understand explaination of a little bit ricky thing ... +1
vik.goel commented: this is so great! thanks +0
Narue 5,707 Bad Cop Team Colleague

For what it's worth, when there's an ambiguity and one can interpret a question as if the OP were either:

  1. A complete idiot
  2. An intelligent person with a reasonable question

I prefer to assume #2 until proven otherwise. Clearly you follow the opposite approach.

Narue 5,707 Bad Cop Team Colleague

Which is not physical.

Thankfully, that wasn't a requirement of the original question. If it was, the OP could have heard our laughing over the internet.

My interpretation of the OPs question is whether the actual amount of RAM can be increased using a file.

No offense, but your interpretation is stupid. Think about it for a moment. Excluding any kind of virtual memory where the appearance of more memory is achieved, the only possible interpretation of the question is physically extending the amount of RAM at the hardware level exactly as if a larger chip were installed. In other words, pure magic.

The type of person who would be so confused about fundamental computing concepts to ask that question, if such a person exists at all, wouldn't be hanging out in a C++ forum.

predator78 commented: you read the question more precisely and you are correct +3
Narue 5,707 Bad Cop Team Colleague

since you are just starting, learn c and c++ first. these are a must learn. if u learn these then you should have no problem in learning others.

Really? So by learning C and C++ I'll have no trouble with LISP, or Haskell, or APL? Sure, learning C and C++ will help with picking up other Algol derivatives a bit more quickly, but that's not the only language family. Sometimes you need to make a huge conceptual leap when learning a new language, and syntax is a very minor part of that.

As for being a must learn. I fail to see why this is the case when the goal is writing smartphone apps. You'd be better off going straight to one of the languages commonly used for such apps, like C#, Java, and Objective-C, depending on which smartphone OS you're targeting. I'm a big proponent of learning C eventually simply for the insights it provides, but not to the exclusion of practicality. If it's not practical to learn C as a first language, don't force yourself.

Narue 5,707 Bad Cop Team Colleague

CountDown::end() doesn't return anything yet you declared it to return bool. That makes you a liar. ;)

Narue 5,707 Bad Cop Team Colleague

&& has higher precedence than ||, so the evaluation looks like this:

if ( (initialize == "off" && Iminor > 20) || Imedium > 10 || Isevere > 5 || Ifatal > 0 )

When what you really want is this:

if ( initialize == "off" && (Iminor > 20 || Imedium > 10 || Isevere > 5 || Ifatal > 0) )
Narue 5,707 Bad Cop Team Colleague

She is, she's using Dev C++ which I have come to hate for many reasons.

Dev-C++ and Code::Blocks use the same underlying compiler (GCC from MinGW). The difference is in the IDE, and that Dev-C++ hasn't been actively worked on for years now, so there would be some default version differences. Standard C++ should work on Dev-C++, regardless of your instructor's request to use pre-standard headers. Though you could verify this, and mention that modern compilers are either in the process of phasing out those headers or have already done so and will refuse to compile code which uses them.

It is the way that our book does it, so that's the way I wan't you to learn it.

Tell her to check the publication date of that book. I'd bet my next paycheck that it's well over a decade old. C++ has evolved since then. You should be asking yourself why you're wasting money learning something that isn't applicable in the real world.

Narue 5,707 Bad Cop Team Colleague

So if I have a stream of 100,000,000 bytes, they're all contiguous in memory?

No. A more likely scenario is that chunks of those characters share the same parts of memory temporarily as they're consumed and the stream buffer is refilled. As far as your concerned, a stream is a queue of characters with very limited out of queue operations like seeking.

Streams have always been a big black box for me as far as what goes on inside.

Yeah, that's the idea. And trust me when I say you really don't want to know. iostream internals is one hell of a can of worms. ;)

VernonDozier commented: Good advice in this thread, as usual +15
Narue 5,707 Bad Cop Team Colleague

Just take away the boost namespace qualification:

#include <iostream>
#include <sstream>
#include <string>
#include <typeinfo>

using namespace std;

template <typename Target, typename Source>
Target lexical_cast(Source arg)
{
    std::stringstream interpreter;
    Target result;
 
    if (!(interpreter << arg && interpreter >> result))
        throw std::bad_cast();
 
    return result;
}

int main()
{
    string string1 = "1";
    string string2 = "2";
    string string3 = lexical_cast<string>(
        lexical_cast<int>(string1) + 
        lexical_cast<int>(string2));

    cout << string1 << " + " << string2 << " = " << string3 << '\n';
}
lexusdominus commented: very informative and useful +3
Narue 5,707 Bad Cop Team Colleague

Look at your "overloaded" constructor. Does it allocate memory? Does it dereference the pointer as if memory were allocated?

predator78 commented: excellent +3
Narue 5,707 Bad Cop Team Colleague

The overload of m_pParent->Log() you're calling isn't defined anywhere that the compiler can see. To start, make sure it has a definition for the type and number of arguments you're passing.

Narue 5,707 Bad Cop Team Colleague

3: Are you posting in the most appropriate place to receive relevant replies? This is the C++ Forum.
YES

This doesn't strike me as a C++ question in the slightest, actually.

Narue 5,707 Bad Cop Team Colleague

I can help with two of your reservations:

  • Objective C is most certainly a unique language. I see it much like C++ in that there's a subset of C, but so robust of an extension to the base that you couldn't compare the two.
  • Objective-C is not limited to the iPhone. It's been around and quite popular for much longer than the iPhone, actually. The language itself is far from a fad, though I don't doubt that an Objective-C forum would attract primarily iOS developers.

I'm not against a new forum, but only if there's a large enough demand.

Narue 5,707 Bad Cop Team Colleague

Wow, that's pretty horrible. Clearly you know how to open and read a file. You also know how to write to one. It looks to me like you're confused about how to check the command line arguments for validity, as well as the specific steps that this program needs to go through:

  1. Validate arguments
  2. Open files
  3. Copy input to output
  4. Close files

Note that if you're expecting two files, argc should not be less than 3. This makes for easy validation:

if (argc < 3) {
    cerr<<"usage: ocopy srcfile destfile";
}
else {
    // Copy srcfile to destfile
}
Narue 5,707 Bad Cop Team Colleague

this just tells the arguments of the CPP file.....

I'm not going to do your homework for you. My example was showing you how to use command line arguments. It's your job to use them for simulating MS-DOS's COPY. Or do you have a specific question that doesn't boil down to "please give me the whole thing"?

Narue 5,707 Bad Cop Team Colleague

Changing the order a bit seems to do the trick. Works now.

It works for the same reason that prototypes work the way they do. If you have a using directive, it applies to everything below the directive, but not above it. Here's an example that takes advantage of this behavior:

#include <ctime>
#include <limits>
#include <random>

namespace jsw {
    template <typename IntT = unsigned, typename EngineT = std::mt19937>
    class mtrand {
        EngineT _engine;
        std::uniform_int_distribution<IntT> _gen;
    public:
        mtrand(const IntT& lbound = std::numeric_limits<IntT>::min(), 
               const IntT& ubound = std::numeric_limits<IntT>::max())
            : _engine((IntT)std::time(nullptr)), _gen(lbound, ubound)
        {}

        IntT operator()() { return _gen(_engine); }
    };
}

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main()
{
    jsw::mtrand<int> rgen(0, 99);
    
    // Use a lambda instead of rgen directly to avoid copying
    generate_n(ostream_iterator<int>(cout, "\n"), 10, [&] { return rgen(); });
}

Two things of note are that the headers are mixed with code, and that the using directive is prior to main, but after the definition of mtrand. This means that mtrand cannot use any names in <algorithm>, <iostream>, or <iterator>, and must explicitly qualify for namespace std. The idea is that the above is easier to work on during initial library development, but by adding inclusion guards, the first part can be split into a header without any headache at all:

#ifndef JSW_MTRAND_H
#define JSW_MTRAND_H

#include <ctime>
#include <limits>
#include <random>

namespace jsw {
    template <typename IntT = unsigned, typename EngineT = std::mt19937>
    class mtrand {
        EngineT _engine;
        std::uniform_int_distribution<IntT> _gen;
    public:
        mtrand(const IntT& …
VernonDozier commented: Good example. +15
Narue 5,707 Bad Cop Team Colleague

It would probably be better to think of the stream as a queue than a string with indices. That way you have the correct perspective of only being able to process it sequentially, whereas strings allow random access.

Narue 5,707 Bad Cop Team Colleague

I have hear many opinions that C is not necessary or even prefered if you are going the route of C++.

If you want to learn C++, learning C first is silly. If you want to be a well rounded programmer, learning C at some point is a good idea. Why? Because C and C++ have different programming styles and idioms. Good C is very likely to be extremely poor C++, so you won't be encouraged to learn the lower level aspects of programming when using C++. With C you have no choice, and being pushed into a fundamentally different way of thinking is enlightening.

That being said I've been starting to become curious about strings and it seems that some C knowledge may be needed or prefered when it comes to strings. Would this be correct to assume?

If you're interested in the underlying aspects of strings, lower level knowledge is helpful, but not necessarily C knowledge. In C++ you're encouraged to use the std::string class instead of char arrays, and even vanilla arrays themselves are falling by the wayside with std::vector and tr1::array (soon to be std::array with C++0x).

However, when learning about the standard library implementations and base libraries in general, you'd be better served with a strong foundation in computer science than experience with any single low/mid level language.

Do I need to concern myself with how sstream works inwardly or can I just learn it's funcionality and forget it?

Learning the functionality …

mike_2000_17 commented: can't add anything to that! +11
predator78 commented: very informative thank you +2
Narue 5,707 Bad Cop Team Colleague

Graphs are typically implemented with an adjacency list or adjacency matrix (google it). If you're feeling especially frisky you can create the graph directly using linked nodes, but that's not necessarily recommended except as an exercise.

Narue 5,707 Bad Cop Team Colleague

I need to add this to the output statement?

SetColors needs to be called with appropriate arguments before the output you want with a different color. It's also not a bad idea to save the current color attributes and restore them when you're done. That's pretty trivial with a sentry object:

#include <iostream>
#include <Windows.h>

class ConsoleColor {
    HANDLE console_handle;
    CONSOLE_SCREEN_BUFFER_INFO saved_info;
public:
    ConsoleColor(WORD foreground, WORD background);
    ~ConsoleColor();
};

ConsoleColor::ConsoleColor(WORD foreground, WORD background)
    : console_handle(GetStdHandle(STD_OUTPUT_HANDLE))
{
    GetConsoleScreenBufferInfo(console_handle, &saved_info);
    SetConsoleTextAttribute(console_handle, foreground | background);
}

ConsoleColor::~ConsoleColor()
{
    SetConsoleTextAttribute(console_handle, saved_info.wAttributes);
}

int main()
{
    std::cout<<"Hello, dull boring normal world\n";

    {
        // Create a color sentry with new colors
        ConsoleColor console_sentry(FOREGROUND_INTENSITY | FOREGROUND_GREEN, 0);

        std::cout<<"Hello, GREEN world!\n";

        // Sentry goes out of scope and restores original colors
    }

    std::cout<<"Back to normal\n";
}
Salem commented: Nice +17
Narue 5,707 Bad Cop Team Colleague

Without getting into the serious issues of your code, the problem is scanf leaving a newline in the stream. gets terminates on a newline, which means it will terminate successfully right away. The most naive solution uses a call to getchar after scanf to eat that newline:

scanf("%d",&n);
getchar();
Narue 5,707 Bad Cop Team Colleague

The standard equivalent of flushall() is fflush(0) . The only thing flushall does is call fflush on all open streams, which is a feature that fflush already supports by passing a null pointer.

There's one caveat though. On implementations where flushall is supported, it typically "flushes" input streams too, where the flushing of an input stream clears all waiting input. This isn't standard behavior for fflush, which means that on implementations where the flushing of an input stream isn't supported, fflush(0) won't be a perfect analog to flushall.

To get a perfect analog on those implementations you need a way of acquiring handles to every open input stream, in which case it's a fairly trivial matter:

#include <cstdio>
#include <ios>
#include <istream>
#include <limits>

namespace jsw {
    using namespace std;

    template <typename CharT>
    void flush_istream(basic_istream<CharT>& in)
    {
        auto eof = char_traits<CharT>::eof();

        if (in.rdbuf()->sungetc() != eof)
            in.ignore(numeric_limits<streamsize>::max());
    }

    void flush_all()
    {
        // Flush all output streams
        std::fflush(nullptr);

        // "Flush" all input streams
        // C++0x ranged-for used for abstractifimication of the stream collection :D
        for (auto& stream : input_streams)
            flush_istream(stream);
    }
}

The actual storing isn't awkward unless you have different character typed streams (such as istream and wistream) in the same program. Just store some kind of handle to the stream in a collection each time you open a new one (not forgetting cin, of course).

Narue 5,707 Bad Cop Team Colleague

When mounting the drive, it's either implicitly or explicitly given a mount point. You use that mount point as the path (it's just a directory). For example using sda1 as the default mount point:

file = fopen("/dev/sda1/file.txt", "a+");

Though it would be a good idea to support a generic mount point in your C code, because the mount point could change with USB devices:

# mkdir /mnt/usbj
# mount /dev/sda1 /mnt/usbj
file = fopen("/mnt/usbj/file.txt", "a+");
Narue 5,707 Bad Cop Team Colleague

An unverified user is one who hasn't yet confirmed their registration from the automated email. Since you likely don't have that email from 2007, I'll see about getting that resent to you.

Narue 5,707 Bad Cop Team Colleague

Average case of building a tree is O(lg n)

You mean O(N logN). Inserting one item into a tree is logarithmic (excluding degenerate cases), but you want to add N items.

So, can this technique be used over others like mergesort , quicksort etc. where the avg case is O(n lg n)???

A tree sort is also O(N logN) provided the tree is either randomized or balanced. But consider all of the extra space and time you're spending to maintain the tree. It's not a bad idea, but not really competitive against the usual suspects for fast general sorting. I'd only use it for cases where I'm already generating a tree, that way the cost isn't quite as prohibitive.

Narue 5,707 Bad Cop Team Colleague

Can I use fread to perform this task?

Yes, but I suspect fscanf is what you want:

int value;

if (fscanf(f, "%d", &value) == 1) {
    /* Successfully read an int value */
}
rEhSi_123 commented: Quick reply and excellent advice +3
Narue 5,707 Bad Cop Team Colleague

There are an infinite number of function signatures.

Narue 5,707 Bad Cop Team Colleague

I'm such a bad person .. :-<

Votes are a pretty subjective thing. You're more likely to get frivolous votes because they're anonymous (haters like this) and don't apply toward reputation (people with strong negative power tend to like this). I doubt anyone thinks you're a bad person because you have more negative votes than positive, though it could be an indicator that you're doing things that aren't approved of.

One example, since you post a lot in the C++ forum, is giving away answers and complete solutions. A lot of us work very hard to teach in a way that forces the student to think and put in a certain measure of effort. Giving away full code and/or the answer to a question makes that effort a waste, and also gives Daniweb the appearance of being a cheater's haven.

Looking at some of your currently negative posts, that seems to be why a number of them were voted down. I suspect that by watching regulars with a high positive rating and following their teaching example, you'd likely have better results yourself.

Narue 5,707 Bad Cop Team Colleague

I already finish scanning file line by line.

This is your first problem.

I write function to split sting using space.

This is your second problem.

You need to take the stream as a whole and recognize tokens as they come character by character. Why? Because the following is perfectly legal C:

int(a)=12345;a*\
=10;

If you only read line by line, you'll have to somehow recognize tokens split across lines. If you rely on tokens being separated by whitespace, that removes a huge amount of common code.

A simple tokenization method is to read from the stream character by character while peeking at the next character, and build a token string. Compare the token string to valid operators, keywords, and literals as you build it, using the peek character to determine if you've completed the longest possible token (C tokenization employs a maximal munch strategy). If the token string isn't an operator, keyword, or literal, treat it as an identifier.

I'd start by incrementally recognizing more and more. So start by recognizing just keywords, then add support for operators, then literals, then identifiers. That way you don't get overwhelmed by all of the different cases.

Narue 5,707 Bad Cop Team Colleague

What have you done so far? We're not going to help you by doing it for you, but we'll be glad to help with any issues when you prove that you've make some kind of honest attempt.

Narue 5,707 Bad Cop Team Colleague

Hi Can you change my username to libertyreservehosting

Can do.

Narue 5,707 Bad Cop Team Colleague

I really have no idea how to do it.

Not paying attention in class, then?

But this is what I have done so far

Which is to say nothing, because all of the member functions are empty. Writing the declarations doesn't really count as doing anything, much as I'd like to debate the necessity of good class interface design.

Narue 5,707 Bad Cop Team Colleague

A friend of mine just informed me that VS 2010 removed the feature where VS keeps the cmd window open when you start w/o debugging.

Your friend is incorrect, though it's no longer a default setting. You can go to the project properties, Configuration -> Linker -> System, and set the subsystem to Console. This will add a pause at the end when running from the IDE.

Narue 5,707 Bad Cop Team Colleague

You shouldn't need a helper with this interface unless the algorithm is recursive. If it's recursive, a helper that takes the current node as an argument is the cleanest solution. In terms of the size member function, it's as simple as a loop (no helper or recursion needed):

size_t priority_queue::size() const
{
    if (_root == 0)
        return 0;

    node *it = _root;
    size_t n = 1;

    while (it->get_next() != 0) {
        it = it->get_next();
        ++n;
    }

    return n;
}

I'm strongly against using recursion for linear problems, so I'd recommend against using recursion in a linked list even if it weren't silly. ;)

Narue 5,707 Bad Cop Team Colleague

opening the output file before the loop doesn't help at all

Ah, I see. You've got a booger of a problem in that both the streams are trying to access the same file. It's generally best not to introduce that kind of concurrency issue, or if you do, be very explicit about how you handle it:

void capital(char file1[])
{
    fstream file(file1, ios::in | ios::out);
    char line[200];

    while (true) {
        // Save the current write position
        fstream::pos_type set = file.tellp();

        if (!file.getline(line, sizeof line))
            break;

        line[0] = toupper(line[0]);

        // Overwrite the old string with the new one
        file.clear();
        file.seekp(set);

        // Be sure to flush so we can safely switch modes
        file<< line <<endl;
    }

    file.close();
    printPoem1(file1);
}
Narue 5,707 Bad Cop Team Colleague

so far I seem to understand how they work "I think" at this stage

I think you're still fuzzy on the distinction between data structures and classes. It helps to think of data structures as more of an abstract concept while classes are a concrete implementation detail. A data structure is really just a pattern of storing and working with data that achieves a specific goal (eg. fast searches).

4. I guess at this point my final thoughts on data structures is that data structures would be a good way to store data that you may not "at the time" know what you may possibly want to do with later on.

On the contrary, data structures are typically selected with a very specific data usage in mind. Occasionally you'll pick a data structure that's "future-proof" and can handle a large number of use cases because you're not entirely sure how the data will react, but for the most part you'll choose from a position of knowledge.

predator78 commented: Narue really understood what I was confused about. +2
Narue 5,707 Bad Cop Team Colleague

Be sure and let him know that. ;)

Jon is the Chuck Norris of C#. ;)

Narue 5,707 Bad Cop Team Colleague

It's the concatenation operator.

Narue 5,707 Bad Cop Team Colleague

Because this constant data ("asd", "QWE", etc.) is stored in a special read-only section in memory you are getting a segmentation fault.

Just a clarification: String literals may be stored in read-only memory. Borland compilers in particular have historically allowed modification of string literals due to not storing the string in read-only memory. The reason the standard allows them to be read-only is twofold:

  1. Compiler writers have the option of placing string literals in a more convenient part of the object file for constant data.
  2. For space saving purposes, string literals with the same contents may point to the same underlying array object.

The provision for allowing read-only string literals is indirect though. The standard says that attempts to modify a shared string literal are undefined, which implies #2 and to a lesser extent #1 since it's a logical precursor to #2.

However, the standard uses tricky wording. It's unspecified whether the array pointed to by a string literal is unique, and an attempt to modify the array invokes undefined behavior, but it's not entirely clear if the undefined behavior is conditional upon the array being shared (though that's my preferred interpretation).

In strictly portable code, it's best practice to assume the most restrictive storage of string literals and treat them as both shared and read-only.

thelamb commented: Hm, did not know it was up to implementers. Thanks for clarifying +7
Narue 5,707 Bad Cop Team Colleague

Everyone has a different opinion. Though I haven't heard much advocacy of C over C++ for "fast" programs. Usually C is viewed as the obsolete parent of C++.

Heard people say c# for big programs, c for fast programs

Big programs cannot be fast?

c++ is just something that failed at being object oreanting c

I have yet to see anyone nail down a concrete, consistent, and agreed upon definition of object orientation that excludes C++. So claiming that C++ failed is a statement of ignorance. Further, it's important to recognize that C++ is not object oriented, though it does support object oriented features, it's multi-paradigm.

is c++ useful?

Given that C++ is probably one of the three most successful programming languages in history (along with COBOL and C), I'd have to say yes, C++ is useful.

Narue 5,707 Bad Cop Team Colleague

You'd still have to put it in a loop:

#include <ios>
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    bool done = false;
    int number;

    while (!done) {
        try {
            cout<<"Enter a number: ";
            if (!(cin>> number))
                throw -1;
            done = true;
        } catch (int) {
            cerr<<"Invalid input\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

    cout<<"You entered "<< number <<'\n';
}

But exception handling is not recommended for "normal" error situations like invalid input. The reason is that the cost of throwing and handling an exception is very high compared to simply recognizing the problem and handling it without throwing an exception.

Narue 5,707 Bad Cop Team Colleague

squareRoot is not declared before it's used. Either move the definition above main, or add a prototype:

#include <iostream>
#include "ArithmeticHeader.h"
using namespace std;

int squareRoot(int number);

int main()
{
Narue 5,707 Bad Cop Team Colleague

I'd tell you, but then I'd have to kill you. ;)