嘿,所以我试图让 pdCurses 库中的 addstr() 与首选字符串类一起工作(Windows curses),所以我使该函数成为以下 string_to_80char() 函数,它应该接受一个字符串并返回一个 80 个字符长的 char 数组(控制台中一行可容纳的字符数),因为这是 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;
}
在函数内部声明 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[])
当然,可能还有其他问题。