Narue 5,707 Bad Cop Team Colleague

Use a vector.

"Without using an array" generally means "without storing all of the numbers", which means vector is out too. But even if you could store all of the numbers, doing so would be stupid because it's trivial to write a linear algorithm without wasting memory like that.

Narue 5,707 Bad Cop Team Colleague

T is a pointer, word is a string. The error explicitly says this.

how i can fix this problem

I'd suggest learning how to use pointers as a general fix, but the specific fix is to dereference the pointer:

*(T[i]) = word;
Narue 5,707 Bad Cop Team Colleague

I've always done it with ADO.NET:

using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;

namespace JSW.Utilities {
    public class ExcelSpreadsheet {
        #region Data Fields
        // Not an auto-property so we can initialize within the getter
        private List<string> _workSheets = null;
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the path of the Excel file
        /// </summary>
        private string FileName { get; set; }

        /// <summary>
        /// Gets or sets the Excel connection string for ADO.NET
        /// </summary>
        private string ConnectionString { get; set; }

        /// <summary>
        /// The contents of the worksheets in the Excel file
        /// </summary>
        /// <remarks>
        /// Worksheets are only loaded when requested and kept in memory afterward
        /// </remarks>
        private DataSet SpreadSheet { get; set; }

        /// <summary>
        /// Gets a list of worksheet names for the Excel file
        /// </summary>
        public List<string> WorkSheets {
            get {
                if (_workSheets != null)
                    return _workSheets;

                _workSheets = new List<string>();

                using (var connection = new OleDbConnection(ConnectionString)) {
                    connection.Open();

                    DataTable schema = connection.GetOleDbSchemaTable(
                        OleDbSchemaGuid.Tables,
                        new object[] { null, null, null, "TABLE" });

                    foreach (DataRow row in schema.Rows)
                        _workSheets.Add(row["TABLE_NAME"].ToString());

                    connection.Close();
                }

                return _workSheets;
            }
        }
        #endregion

        #region Indexers
        /// <summary>
        /// Gets a worksheet from the Excel file by name
        /// </summary>
        /// <param name="sheetName">Name of the desired worksheet</param>
        /// <returns>The worksheet as a data table</returns>
        public DataTable this[string sheetName] {
            get {
                // Don't reload the worksheet if it's already in memory
                if (SpreadSheet.Tables.Contains(sheetName))
                    return SpreadSheet.Tables[sheetName];

                var table = new DataTable(sheetName);
                string query = "select * from …
kvprajapati commented: :) +15
Narue 5,707 Bad Cop Team Colleague

Don't use the standard libraries with the .h extension, they are out-dated (pre-1998) and are only kept around for backward compatibility

Technically they're deprecated, but realistically that's a bluff. Even if the standard committee smokes a huge doobie and removes the old C headers in their stoned haze, compiler vendors will collectively give them the finger.

I wouldn't expect them to be updated to work fully on newer implementations (OS).

How do you figure that? They're a part of the standard, so they're required to work "fully" on any conforming implementation.

Use the following headers instead:

Which does little more than wrap the other headers in namespace std[1], so your previous statements seem a little weak. ;) That's not to say that the new headers aren't desirable for consistency and avoiding name collisions. You're also future proofing in the amazingly unlikely case that the old headers are removed from the standard.

Socratic Questioning:

And it is bad practice to use C functions in C++.

Why?

Use the iostream library instead of those old C functions (fopen, fwrite, fclose). Replace your code with this C++ equivalent:

And what does the "C++ equivalent"[2] buy you? Actually, let's modify that question a bit. What does foo() enjoy that bar() does not (aside from claims of C++ "purity"):

void foo(const some_struct& x)
{
    ofstream f("data.txt", ios::out | ios::binary);

    if (f)
        f.write((char*)&x, sizeof x);
}
void bar(const some_struct& x)
{
    FILE *f = fopen("data.txt", "wb");

    if (f != NULL) …
Narue 5,707 Bad Cop Team Colleague

Change this

for(d=z; d>=1; d--)

to this

for(d=x; d>x-z; d--)

Now tell me why that works and what you were doing wrong. :)

Narue 5,707 Bad Cop Team Colleague

I know I probably have to use some sort of while loop to search for a null.

Yes, you're searching the string for words, so some sort of loop will be involved. Think about how you might do it manually given only a look at one character at a time.

Given "this is a test":

't': It's not whitespace. We're not in a word, so capitalize it.
'h': It's not whitespace. But we're in a word, so leave it.
'i': It's not whitespace. But we're in a word, so leave it.
's': It's not whitespace. But we're in a word, so leave it.
' ': It's whitespace, so we're not in a word anymore.
'i': It's not whitespace. We're not in a word, so capitalize it.
's': It's not whitespace. But we're in a word, so leave it.
' ': It's whitespace, so we're not in a word anymore.
'a': It's not whitespace. We're not in a word, so capitalize it.
' ': It's whitespace, so we're not in a word anymore.
't': It's not whitespace. We're not in a word, so capitalize it.
'e': It's not whitespace. But we're in a word, so leave it.
's': It's not whitespace. But we're in a word, so leave it.
't': It's not whitespace. But we're in a word, so leave it.
'\0': String terminator, we're done!

So what do you need to accomplish this algorithm? You need to be able to determine if a single character denotes whitespace, and …

Narue 5,707 Bad Cop Team Colleague

i'm studying with a really old school c programmer

While his code may be shit, I wouldn't recommend inheriting that particular trait.

who kind of wants me to go through the basics [thinks it will encourage good practices] so he probably would want to see me use *ptr ...

Yeah? How about *ptr = toupper(*ptr); ? Using pointer operations for educational purposes doesn't excuse otherwise bad code in this case.

Salem commented: Yes +17
Narue 5,707 Bad Cop Team Colleague

Old threads are not automatically closed because there's no reason why the discussion could not be continued profitably by newcomers. We've discussed the issue of bumping before, and concluded that it's not enough of an issue to introduce such heavy handed methods.

However, bumping is indeed frowned upon if the new post contains nothing that adds to the thread. The reason it's frowned upon is because bumping a thread that was not originally on page 1 of the forum will drop a thread that was to page 2. Falling to page 2 is the kiss of death for a thread, and it's completely unfair to the OP.

As such, I prefer to delete bumps (without applying an infraction or warning) unless they have significant value. "Thank you" and "me too" posts do not fall under that category, so I would suggest reporting them as you see them.

It does bother me because most of them are signature spammers

That's another issue entirely. Spammers should be reported so that they can be banned as quickly as possible.

happygeek commented: yep +0
Narue 5,707 Bad Cop Team Colleague

Also note that the lambda return type can be deduced in this case, explicitly specifying it is unnecessary:

my_list.remove_if([](int x) { return x == 4; });
mike_2000_17 commented: Already an expert in C++0x... you're awesome! +11
Narue 5,707 Bad Cop Team Colleague

You can't. It's a static string and cannot be modified.

Aroo? prose is an array initialized with a string literal, it can most certainly be modified.

>*ptr = *ptr-32;

Good god, are people still doing this? The world is not ASCII anymore, folks, use toupper() if you want to be one of the cool kids.

Narue 5,707 Bad Cop Team Colleague

I typically make a Types.h to define all of my types in and then include that in all of my project files. I haven't ever seen this anywhere though, so I assume it is "bad/wrong".

I do that occasionally as well, though that's not proof that it isn't "bad/wrong". ;) It's not so much the idea, but the extent that matters. Putting all of your type definitions into a header for the sake of keeping them centralized, regardless of whether that makes sense, would be a design stink. But centralizing related type definitions that are used in multiple translation units is sensible.

Consider a class Gardener that needs to know type of grass he will be cutting. Then consider a class Lawnmower that also needs to know what type of grass will be cut. What I would have done in the past is put typedef float GrassType; in Types.h and then included Types.h from Gardener.h and Lawnmower.h.

My gut reaction is to ask why Gardener and Lawnmower care about the type of grass. But let's assume that it makes sense for them to depend on the type of the grass, wouldn't that be a reasonable place for a template?

Is there a better way to do this than to introduce a template parameter to Lawnmower that can be set by the Gardener that owns it?

Redesign your classes so that the type of grass doesn't matter? ;) For this abstraction, I really don't see the need. The only …

Narue 5,707 Bad Cop Team Colleague

And your immediate problem is what, exactly? You neglected to actually ask a question.

Salem commented: indeed +17
Narue 5,707 Bad Cop Team Colleague

For writing 1D barcodes without any special encoding, such as 3 of 9[1], you can download the appropriate font from somewhere and then simply draw the barcode on an image:

Bitmap DrawText(string value, string fontName, float size) {
    using (var font = new Font(fontName, size, FontStyle.Regular, GraphicsUnit.Point)) {
        var image = new Bitmap(1, 1);

        using (var g = Graphics.FromImage(image))
            image = new Bitmap(image, g.MeasureString(value, font).ToSize());

        using (var g = Graphics.FromImage(image)) {
            g.Clear(Color.White);
            g.DrawString(value, font, new SolidBrush(Color.Black), 0, 0);
            g.Flush();
        }

        return image;
    }
}
pictureBox1.Image = DrawText("*" + value + "*", "3 of 9 Font", size);

Unfortunately, you can't do that for 2D barcodes because there's a significant amount of work in encoding the data. Now, you could become an expert on barcode formats and image processing, then write your own code for doing this stuff manually, but that's kind of silly. A much better option is to use an existing library for reading and writing barcodes.

I'm not terribly familiar with the freely available libraries, but google will help you with that. However, if you don't mind a commercial library, I'd recommend both Atalasoft and Vintasoft.


[1] Yes, 3 of 9 uses asterisks as the start and stop character, but that's hardly what I'd call "special" encoding. What I mean by special encoding is the complex algorithms involved in a format such as PDF417.

Narue 5,707 Bad Cop Team Colleague

Graphic design.

Defend your answer.

Narue 5,707 Bad Cop Team Colleague

We don't do homework here. Please make an attempt yourself if you want help.

Salem commented: *nods* +17
Narue 5,707 Bad Cop Team Colleague

Why is it a bad idea to use the std namespace for my new functions?

If you mean something like this:

namespace std {
   // Add myfunction() to namespace std
   void myfunction();
}

It's a bad idea because doing so invokes undefined behavior. If you mean something else, please clarify.

If all of my functions have names which are different than the names of std functions, it is no harm, right?

Hmm, how do you know all of your names are different? Why even bother cross referencing with the standard (and any other libraries you use) when you could just create a unique namespace and not worry about it?

Narue 5,707 Bad Cop Team Colleague

Yea... Didn't understand much of that...

If you understood it, you wouldn't have asked how stringstreams work. Figure it out and you'll learn something. I'm not going to spoon feed you everything, but I'll answer any specific questions you have.

How it does the conversion.

Deep down it does the conversion much like atoi, the implementation of which is a very common beginner's exercise. Might I suggest googling it?

Salem commented: Well said +17
Narue 5,707 Bad Cop Team Colleague

If you check syria's second post that includes his code it says "char main()" so I assumed it was correct

Yeah, it's not really the best practice to assume any kind of correctness from the code of obvious novices. ;) But hey, you can use this as a heads up to research things such as the valid definition of main(). Win.

Salem commented: win indeed +17
Narue 5,707 Bad Cop Team Colleague

Note that scanf is converting the display representation to the value, so %d will look for decimal values. %x will allow you to read hexadecimal values.

Narue 5,707 Bad Cop Team Colleague

Hi,
I am writing an application in which I make
a map of strategies keyed by a string symbol. In
order to construct the strategies I pass the constructor
a filename, out of which it reads out some data, into an initializing map.

It is possible that some data might be missing from the initializing map,
in which case I simply want to skip this strategy. I am
thinking that, to implement this I need to throw an exception
if the data is missing. But I am unsure how to implement this, as
I have never used exceptions before.

Throwing an exception is one option, but is this truly an error condition? You're just catching the exception and swallowing it, which suggests alternative strategies. For example, a factory can be used to verify the file and pass the verified data into a private constructor. That way you can simply return a null pointer if the file is bogus rather than throw an exception:

class TradingStrategy {
    ...
public:
    static TradingStrategy *create(const string& file);
private:
    TradingStrategy(map<string, string> initMap);
};

TradingStrategy *TradingStrategy::create(const string& file)
{
    map<string, string> tempMap;
    
    // Initialize tempMap from the file
    
    if (tempMap.find("MuSCurve") == tempMap.end())
        return 0;
        
    return new TradingStrategy(tempMap);
}
while (symbolStream >> symbol) {
    TradingStrategy *ts = TradingStrategy::create(calFileDirectory_ + symbol);

    if (ts != 0)
        _strategies[symbol] = ts;
}

The issue here is that your TradingStrategy class is actually doing two things:

  • Parsing a file
  • Managing a …
Narue 5,707 Bad Cop Team Colleague

Let me get this straight. You have a final year project about a topic that was never covered in any way, shape, or form during the course? I strongly doubt that. It's more likely that you simply didn't pay attention and deserve to get a failing grade.

Narue 5,707 Bad Cop Team Colleague

The size of a character depends on the encoding for your character set. Do some research on ASCII and Unicode for details.

Narue 5,707 Bad Cop Team Colleague

This thread is going nowhere and will only serve as leech bait, so I'm closing it.

Narue 5,707 Bad Cop Team Colleague

thus iterators predefined functions?

Iterators are a concept for range access with a design derived from pointers, where a concept is a set of requirements for accessing the range. For example, find() and for_each() can both be written with a minimal set of requirements (assumptions about the "pointer" type):

template <typename Iterator, typename T>
Iterator find(Iterator first, Iterator last, const T& value)
{
    while (first != last && *first != value)
        ++first;

    return first;
}
template <typename Iterator, class Action>
Action for_each(Iterator first, Iterator last, Action f)
{
    while (first != last)
        f(*first++);

    return f;
}

Notice that there's absolutely nothing that forces the Iterator template type to adhere to the concept, but the concept requirements for Iterator in both of these functions are easily seen:

  • Iterator must be copy-assignable (to pass as an argument by value)
  • Iterator must be equality comparable
  • Iterator must support indirection.
  • Iterator must support incrementing (pre and post).

Iterators are thus just a set of requirements sanctioned by the standard for maximum reuse among the standard algorithms and to make extending the standard algorithms with your own functions easier.

It's somewhat confusing because iterators aren't functions or types, or anything more than an idea, really. They don't take shape until you model the concept with a type that conforms to the requirements. You're not forced to model the concept exactly either, just the parts you know will be used.

I am confuse between function and predefined functions.

Let's …

Salem commented: Nice +17
Narue 5,707 Bad Cop Team Colleague

Use the command line and an editor while you're learning C.

Because then you don't have to learn how the editor works, or how to invoke the compiler to do what you want. Oh wait, yes you do. There's a learning curve either way, so saying not to use an IDE because you'll have to learn how to use it is silly.

Everyone should use command line tools for a little while to have a better idea of what the IDE is doing for them, and so that they're not dependent on an IDE. However, once that little insight is learned, an IDE is generally the way to go.

Narue 5,707 Bad Cop Team Colleague

Yes you are right, i already had & into the two pointers but i copied the code from the old file were missing.

It couldn't hurt to make sure that your question and code are both up-to-date before posting. Otherwise you cause people to waste their time solving problems that don't exist.

The problem that i have is that the function doesn't search on all right nodes.

Note that you neglected to specify what the problem was in your first post. So don't be surprised that I fixed the most obvious issue.

Salem commented: <teal'c>indeed</teal'c> +17
Narue 5,707 Bad Cop Team Colleague

anyone can you help me to my C++ i cant take the error everytime i make a program i got error and can you give me a program that can solve the area of Circle In Turbo C. thanks

...

Narue 5,707 Bad Cop Team Colleague

I know how to solve your problem, but the exercise isn't about getting someone else to do your work for you, is it? Were I you, I'd start by studying up on how the predefined functions work to get a better idea of the algorithm at play.

Salem commented: +1 +17
Narue 5,707 Bad Cop Team Colleague

But caution: computer programming and drinking don't mix.

False. My code while under the influence is the stuff of legends. The only drawback is that it rots quickly, like in a couple of hours or so. ;)

Narue 5,707 Bad Cop Team Colleague

KeyboardProc was used before it was declared (C++ parses from the top down). You can either add a prototype before installhook(), or move the definition of KeyboardProc to be before installhook().

As for GetKeyState, you misspelled it:

#include<windows.h>

static HHOOK hkb=NULL;
HANDLE h;

BOOL __stdcall DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) 
{
    h=hModule;
    return TRUE;
}

LRESULT __declspec(dllexport)__stdcall KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) 
{
    short int state;

    if(nCode<0)
        return CallNextHookEx(hkb, nCode, wParam, lParam);

    if((nCode==HC_ACTION)&&((DWORD)lParam&0*40000000)) {
        state=GetKeyState(VK_CAPITAL);
        if((state&1)==0) {
            keybd_event(VK_CAPITAL,0,KEYEVENTF_EXTENDEDKEY,0);
            keybd_event(VK_CAPITAL,0,KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP,0);
        }
    }
    return CallNextHookEx(hkb, nCode, wParam, lParam);
}

BOOL __declspec(dllexport)installhook() 
{
    hkb=SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, (HINSTANCE)h,0);
    if(hkb==NULL)
        return FALSE;

    return TRUE;
}

BOOL __declspec(dllexport) removehook() 
{
    return UnhookWindowsHookEx(hkb);
}
Narue 5,707 Bad Cop Team Colleague

1) Is the extraction operator using the get() function in case of fstream?

Probably not. More likely is that it uses the member functions of the stream buffer directly (just like get()).

2) Does moving the file pointer imply another call to seekg()?

No, the file pointer is at a much lower level than seekg().

3) Would this mean stringstream's get() function would be faster?

It's fairly safe to assume that stringstream's get() function is faster, but that's because you're accessing strings in memory rather than hardware.

4) Would this 'ss << std::fstream ("file.xml",std::ios::in).rdbuf();' be faster than both operations since the buffer is already filled?

Well, obviously it comes down to the quality of the implementation, but writing the stream buffer is typically the fastest way to dump the contents of a stream.

Narue 5,707 Bad Cop Team Colleague

I found a page saying that int a = 12; and int a (12); do the same thing.

Indeed. There's also a third way in C++0x (where the added functionality prevents narrowing conversions):

int a{12}; // alternatively 'int a = {12};'

But is there something special with the int a (12); way of initializing a variables?

Sometimes it's the only way. One example would be in a constructor's initialization list. Another is for user-defined types that have an explicit constructor, the assignment initialization syntax is disallowed:

class foo {
public:
    foo(int) {}
};

class bar {
public:
    explicit bar(int) {}
};

int main()
{
    foo a = 11; // Okay, non-explicit constructor
    bar b = 11; // Error! Implicit construction not allowed
}

The constructor initialization can also introduce an ambiguity between a variable definition and a function declaration:

int a(int());

You might guess that this defines an int variable called a and initializes it with the default value of int. What it really does is declare a function called a that takes an unnamed int parameter and returns int.

Like, you can do: string test(5, '-'); which would make test = -----
I couldn't seem to find a way to do the same using string the test = way.

Correct. The assignment initialization only applies to "constructors" with a single parameter. I say "constructors" because the built-in types don't have constructors, yet the syntax still behaves as if they did.

mike_2000_17 commented: for mentioning function decl. syntax conflict +11
Narue 5,707 Bad Cop Team Colleague

Good god, are you really that clueless? It's the same damn thing as Insensus' example, just with GetTickCount() instead of time():

#include <iostream>
#include <windows.h>
 
int main()
{
    DWORD before = GetTickCount();
 
    std::cin.get();
 
    std::cout << GetTickCount() - before << " milliseconds passed";
}
Salem commented: Getting there in the end +17
Narue 5,707 Bad Cop Team Colleague

The ctime library only supports a granularity down to seconds. For milliseconds you must either use a non-portable library (such as GetTickCount()). The Boost Date_Time library offers sub-second resolution if the underlying platform does as well (which Windows does).

Standard solutions include dividing the result by CLOCKS_PER_SEC (be sure to cast either of the operands to double) and hoping for the best, or taking advantage of the new <chrono> stuff in C++0x. Both are non-portable at this time. The former is unconditionally non-portable and the latter depends on adoption of the upcoming standard in compilers.

Narue 5,707 Bad Cop Team Colleague

Are you using the correct format string for ParseExact()? Also note that if you just want to verify the formatting, TryParseExact() would be a better option due to returning bool instead of throwing an exception on failure:

CultureInfo culture = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.AssumeLocal;
string time = "44:22.37";
DateTime dummy;

if (DateTime.TryParseExact(time, "mm:ss.ff", culture, style, out dummy))
    Console.WriteLine(dummy.ToString("mm:ss.ff"));
Narue 5,707 Bad Cop Team Colleague

>#ifndef __IN_HEADERNAME
>#define __IN_HEADERNAME

The rules for leading underscores in names can be tricky, and it's easy to stomp all over the implementation's reserved identifiers. Unless you're intimately familiar with the rules (which you're clearly not), I'd recommend not using any leading underscores at all.

Narue 5,707 Bad Cop Team Colleague

By "doesn't seem to work" do you mean it fails to compile with an error along the lines of "'gotoxy' was not declared in this scope"? Because that's what I would expect, since gotoxy is one of those conio functions that isn't likely to be supported except on Borland compilers.

Since you're working on Windows, you might as well use something that's more likely to work with your compiler:

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

using namespace std;

namespace support_for_ancient_techniqes {
    void gotoxy(SHORT x, SHORT y )
    {
        COORD coord = {x, y};
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    }
}

int main()
{
    cout << "Here..." << flush;
    support_for_ancient_techniqes::gotoxy(12,8);
    cout << "And now here..." << flush;
}
NathanOliver commented: awsome namespace name +9
Narue 5,707 Bad Cop Team Colleague

I want to how and why given program run?

Why don't you keep reading the standard? It has the answers:

A return statement with an expression shall not appear in a function whose return type is void.

Violation of a "shall" constraint invokes undefined behavior, which is defined as:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

Translation: Anything can happen. If your compiler isn't nice enough to halt compilation when you do stupid shit, "anything" includes running. The answer to your question is that you got lucky (or unlucky, depending on how you view completely unpredictable behavior).

Salem commented: Well said +17
Narue 5,707 Bad Cop Team Colleague

May someone please explain to me why the rename function isn't working?

rename() sets errno. Call perror() to get a more useful error message.

Salem commented: Yes +17
Narue 5,707 Bad Cop Team Colleague

Okay, instead of just guessing and writing random stuff, go read a C++ reference on handling exceptions. Or search google. Of course, there's still the issue of trying to allocate exorbitant amounts of memory.

Salem commented: It was an easy walk to get past AD, now for the long climb to the #1 spot +17
Narue 5,707 Bad Cop Team Colleague

I find that programming skills will develop along the way.

It's really the other way around. Focus on programming skills and language/library knowledge will develop along the way.

Salem commented: Yes +17
Narue 5,707 Bad Cop Team Colleague

I'm 18 with tons of free time.

I've been working with C almost obsessively for 15 years and haven't hit the bottom yet.

So reading what THE C book isn't also going to take up all of C's features?

Is your goal is to be book smart without any actual programming ability?

Salem commented: There is no bottom, it's a void :) +17
Narue 5,707 Bad Cop Team Colleague

I feel no urgency at all. Your thread is mistitled.

Salem commented: Likewise +17
Narue 5,707 Bad Cop Team Colleague

But does the whole feature set and everything C has to offer end with what 'how to' books give?

No. "How to" books teach the most useful or widely used subset of features (sometimes not even that much). Those books generally cater to beginners, who would be overwhelmed by everything C has to offer. Further, knowing the features of the language is a long way from knowing how to use them effectively.

What is 'C' then?

C is the language and library definition provided by ISO (a draft of the standard can be found here, but it's not light reading).

I tried opening some header files and god knows what those things mean.

You shouldn't expect to understand those things yet. Real world code will look wildly different from the toy programs you're used to because real world code needs to be robust in the presence of errors, needs to handle hardware and software bugs/incompatibilities, and performance (both memory usage and CPU usage) must be finely tuned.

It bugs me how on earth can they make those APIs using the standard library because I'm confident they can't

You're right, and for the most part they can't. The majority of libraries and APIs cannot be written without platform or hardware dependencies. While getting by with just the standard library is a noble goal, it's often simply not possible. But that doesn't mean you can't call platform dependent libraries, like POSIX or the Win32 API to do …

Aia commented: Deserves credit +14
Narue 5,707 Bad Cop Team Colleague

Four years of education doesn't buy you much, does it? You can't even think of a topic on your own.

Salem commented: You've got 'god' mode, do something like delete all topics with 'thesis' in the title so it no longer features in google search results as a place to post topics with a subject of 'thesis title' +17
Narue 5,707 Bad Cop Team Colleague

To the question above yes.

Okay, that's not a copy, it's a translation. The problem is that you can't use getline to do it because getline doesn't recognize newline configurations that aren't for the compiler's target platform. In other words, getline will recognize CRLF on Windows, but not just CR or just LF. So you won't get the correct splitting of lines.

This is a case where the translation is rather manual on two binary streams:

#include <fstream>

using namespace std;

int main()
{
    ifstream in("source", ios::binary);

    if (in) {
        ofstream out("destination", ios::binary);
        char ch;

        while (in.get(ch)) {
            if (ch != '\r')
                out.put(ch);
            else {
                // Assume all carriage returns mark a newline
                out << "\r\n";

                // Trim a line feed because we just wrote it
                if (in.peek() == '\n')
                    in.ignore();
            }
        }
    }
}
Narue 5,707 Bad Cop Team Colleague

My question does anyone know a way of copying from one file to another.

Are you reading impaired? I gave you a short program that performs an exact copy of a file. All you need to do is incorporate that into your code, and nothing extra needs to be done to handle rogue carriage returns.

Salem commented: + +17
Narue 5,707 Bad Cop Team Colleague

Does anyone know how to cpy from one file and redirect to another.

#include <fstream>

using namespace std;

int main()
{
    ifstream in("source", ios::binary);
    ofstream out("destination", ios::binary);

    if (in)
        out << in.rdbuf();
}

I need the Carriage return (0D) to be present.

Text mode streams will convert whatever platform dependent line break method is used into '\n' on reading and back on writing. Your requirement makes no sense to me, but if you want an exact copy of a file, open the streams in binary mode.

Narue 5,707 Bad Cop Team Colleague

I have a better idea. You tell us what problem you're trying to solve, and we'll help you come up with a better algorithm.

Salem commented: + +17
Narue 5,707 Bad Cop Team Colleague

Put it in your gcc invocation:

all: run
 
 
test: test.c
	gcc -D HELLO test.c -o test
 
run: test
	./test
 
clean:
	rm *~ *.o test
VernonDozier commented: :) +15