开发者

how can i initialize a dynamically allocated array of characters so i don't get those weird characters?

I want to use that array of characters in my game of "hangman" to view to tha user his current progress. 开发者_如何转开发

#include <iostream>
#include "randword.h"
#include <fstream>
#include <time.h>
#include <cstdlib>

using namespace std;



int main()
{
InitDictionary();
string tixaio=Randomword();
int m = tixaio.length();
int guesses=8;
char *charptr= new char[m];





for(int aa=0;aa<m;aa++){
charptr[aa]='-';

}

cout << "The word now looks like this: "<<charptr;


}

As soon as i try to cout<< charptr my array i got the usual "---------" plus some weird characters. How can i prevent those characters from showing up??


Strings in C and C++ must end in a "\0" character: a character that is the value 0.

However, you should be using std::string instead of an array of characters. Then you won't have to worry about ending in a null character.


When you print an array of characters in C++, cout (or any ofstream object, for that matter) looks for the null terminating character to determine when to stop printing. Now, if you've only allocated m bytes for the array, and cout tries to access memory outside of those m bytes, you could possibly even get a segmentation fault.

One way to avoid this is to allocate space for one more character than what's needed, and assign '\0' to that extra character.

char *charptr= new char[m+1];
charptr[m] = '\0';

Since you're using C++, it has a built in std::string class which you can use for your purpose. It automatically appends the null terminating character to the string. This behavior can be verified by calling the c_str() function on an object of type std::string (this converts std::string to char*). It'll always return n+1 characters, where n is the number returned by std::string's length() function. And as you can guess, the last character will be \0.


It's a char *, AFAIK you need to have a \0 terminator at the end so that the printing knows when to stop.


clear the array to 0

memset (array, 0, size);

Or after you make the string, append a '\0' just after the end of the string, which will indicate the end of string. This will prevent the printing routing go beyond the limit which you want. In your case you should place charptr[aa] = '\0' just after the for loop. Make sure that you have enough allocated memory block to charptr you need to allocate the length of string + 1 (for the '\0' character).


you have to insert the '\0' character at the end since it's a null terminated string


You should add a \0 as the last element after you fill up the array.

Better option is to use std:;string that is the C++ way of doing things better and in a elegant manner, without having to bother about null terminating as in case of char*

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜