0

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.

3
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by Mashadar
0

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.

1

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

Votes + Comments
Heh, that was really interesting.
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.