开发者

Curses string and char manipulation problems

Hey so i'm trying to get addstr() in the pdCurses library to work (windows curses) with the preferred string class so i made the function the following string_to_80char() function, which is supposed to take a string and return an 80 character long char array (the number of characters fit on one line in the console) since this is the only parameter addstr seems to accept...

However when running the following code i do get the "Just a string" printed but with a random character like an '@' or '4' like 50 spaces after it.....

WHATS THE PROBLEM?? THanks for the help! =)

#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(); // c开发者_开发问答urses 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;
}


You declare charArray inside of a function and then return a pointer to it. Outside of the function, that memory is out of scope, and should not be referenced.

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

Ditto for the error string.
You could pass in charArray to string_to_80char and write to that.

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

Of course, there still might be other issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜