1

I've never seen anything like this before and I can't figure out what could possibly be causing it. This is HW so you don't have to fix it for me just give me a clue whats going wrong. Here is my code.

void countChars(ifstream& inData, string filename, char x[])
{
for(int i=0; i < 58; i++)
    x[i] = 33+i;

cout << x << endl;
}

here is my output

output

user2087867
  • 95
  • 1
  • 9

2 Answers2

4

You forgot to null terminate your char[].

std::cout.operator<<(char*) uses \0 to tell where to stop.

This is a duplicate of: this

Community
  • 1
  • 1
ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34
  • thank you. we can't use std:: stuff yet since we haven't learned it but I understand it better now that you explained it that way – user2087867 Dec 03 '13 at 02:08
  • 1
    @user2087867 Np, schools / unis can't teach C++, speaking from my own experience. All of the operators are really just function calls. – ScarletAmaranth Dec 03 '13 at 02:21
1

add a x[58] = 0; before the cout.

RichardPlunkett
  • 2,998
  • 14
  • 14
  • 1
    That kind of works but I get an error that says the stack around chararray has been corrupted. – user2087867 Dec 03 '13 at 02:22
  • Yeah, @Richard, this is unsafe advice unless you qualify it by reminding the OP to make sure the array is big enough for an extra `char`. You've just taught the OP to write a buffer overrun into his code. – Lightness Races in Orbit Dec 03 '13 at 13:17