2011-05-08 15 views
0

ちょっと、私は、希望の文字列クラスで動作するようにpdCursesライブラリ(Windows Curses)のaddstr()を取得しようとしていますので、次のstring_to_80char()関数を作成しました。これが唯一のパラメータであるため、文字列を取り、80文字の長さのchar配列(コンソールの1行に収まる文字の数)を返すようにしてください...Cursesの文字列と文字の操作の問題

ただし、次のコードを実行すると"@"または "4"のようなランダムな文字が印刷された後、 "Just a string"が得られます。

問題は何ですか?助けてくれてありがとう! =)

#include <curses.h>   /* ncurses.h includes stdio.h */ 
#include <string> 
#include <vector> 
#include <Windows.h> 
#include <iostream> 
using namespace std; 

char* string_to_80char (const string& aString) 
{ 
    int stringSize = aString.size(); 
    char charArray[90]; 

    if(stringSize <= 80) 
    { 
    for(int I = 0; I< stringSize; I++) 
     charArray[I] = aString[I]; 
    for(int I = stringSize; I < sizeof(charArray); I++) 
     charArray [I] = ' '; 
    return charArray; 
    } 

    else 
    { 
    char error[] = {"STRING TOO LONG"}; 
    return error; 
    } 
}; 


int main() 
{ 
    // A bunch of Curses API set up: 
    WINDOW *wnd; 

wnd = initscr(); // curses call to initialize window and curses mode 
cbreak(); // curses call to set no waiting for Enter key 
noecho(); // curses call to set no echoing 

std::string mesg[]= {"Just a string"};  /* message to be appeared on the screen */ 
int row,col;    /* to store the number of rows and * 
        * the number of colums of the screen */ 
getmaxyx(stdscr,row,col);  /* get the number of rows and columns */ 
clear(); // curses call to clear screen, send cursor to position (0,0) 

string test = string_to_80char(mesg[0]); 
char* test2 = string_to_80char(mesg[0]); 
int test3 = test.size(); 
int test4 = test.length(); 
int test5 = sizeof(test2); 
int test6 = sizeof(test); 

addstr(string_to_80char(mesg[0])); 
refresh(); 
getch(); 


cout << endl << "Try resizing your window(if possible) and then run this program again"; 
    system("PAUSE"); 
refresh(); 
    system("PAUSE"); 

endwin(); 
return 0; 
} 
+1

[pdCURSESとaddstrとの文字列の互換性問題の可能な複製](http://stackoverflow.com/questions/5925510/pdcurses-and-addstr-compatibility-with-strings-problems) – casperOne

答えて

1

charArrayを関数内で宣言し、そのポインタを返します。関数外では、そのメモリは有効範囲外であり、参照されるべきではありません。

char* string_to_80char (const string& aString) 
{ 
    ... 
    char charArray[90]; 
    ... 
    return charArray 
} 

エラー文字列については、
charArrayをstring_to_80charに渡してそれに書き込むことができます。

void string_to_80char (const string& aString, char charArray[]) 

もちろん、その他の問題がある可能性があります。