2011-05-08 62 views
0

嘿所以我試圖讓ptrCurses庫中的addstr()與首選字符串類工作(Windows詛咒),所以我做了以下函數string_to_80char()函數,這是應該的取一個字符串並返回一個長度爲80個字符的字符數組(字符數適合控制檯中的一行),因爲這是唯一的參數addstr似乎接受...詛咒字符串和字符操作問題

但是,當運行以下代碼時得到「只是一串」印刷,但隨機字符像一個'@'或'4'像50個空格後.....

什麼問題?謝謝您的幫助! =)

#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 2011-05-08 20:22:43

回答

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[]) 

當然,還可能有其他問題。