Hi,

I have created an on-the-side project to test some code which I hope to merge with my main program, however I've noticed that the output generated varies between two compilers (VC++ 2005 Express and Dev-C++). Since I am doing the project in VC++, it's output has had me scratching my head for some time now. I would be extremely grateful if anyone can suggest a reason for the inconsistency between the two compilers.

VC++ Input:

Enter: a 2 3

a 2 3²²²²½½½½½½½½■ε■ε■ε■

Dev-C++ Input:

Enter: a 2 3

a 2 3

The code used in both compilers:

#include <string>
#include <iostream>

using namespace std;

void standardInput(string command);

int main()
{
    string tempStr;
    
    cout << "Enter: ";
    cin >> tempStr;
    cout << endl;
    
    standardInput(tempStr);
    cin.get();
}

void standardInput(string command)
{
    char *line;
    string strLine;
    int length;

    getline(cin, strLine);
    strLine.insert(0,command);
    length = strLine.length();
    
    line = new char[length];
    memset(line,'\0',length);
    strLine.copy(line,length);

    cout << line << endl;
    delete [] line;
}

Thanks for any input, at all.

Recommended Answers

All 4 Replies

Your string's not null-terminated, unless you're lucky. In Dev-C++, it turns out that a zero was already there at the end of the string 'line'. In VC++'s executable, that turned out not to be the case.

You need to use

line = new char[length + 1];
strLine.copy(line,length);
line[length] = '\0';

in place of what you have there.

What you're doing is setting the characters to zero and then overwriting all the zeros you wrote, which is just pointless. You need a zero _after_ the C-style string, to delimit its end, so you need to allocate one extra byte for that zero and then set it to zero.

Member Avatar for iamthwee

Don't have the MS compiler here, but can't he/she just use the .c_str() command?

He could just cout the string itself, so I take it this is just a test program for another project.

commented: Heh, that was really interesting. +18

line = new char[length + 1];
strLine.copy(line,length);
line[length] = '\0';

Thanks a bunch, champ -- that worked like a charm.. I was banging my head against the wall for hours wondering why that wouldn't work in VC++. Much appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.