Я застрял в этом вопросе несколько недель и не понимаю его. Я думаю, что единственный способ правильно показать, что происходит, — это объяснить все это.
Цель
Я создаю программу для ncurses, которая позволяет мне брать символы из отдельного файла и печатать их на экране в определенном месте. В настоящее время я реализую поддержку символов UTF-8, поэтому текстовое оформление может быть более интересным, поскольку доступно гораздо больше символов, чем просто ASCII.
Важные выводы
Поскольку я работаю в macOS, ncurses напрямую не поддерживает широкие символы. Однако я обнаружил, что могу использовать addstr() для печати широких символов. По этой причине я разработал программу, использующую addstr() вместо addch().
Программа
Эта программа в основном состоит из одной функции — штамп(). Это функция, которую я создал для ncurses, чтобы упростить размещение текста на экране. Это делается в несколько шагов:
- Открыть выбранный текстовый файл.
- Ввести цикл, который считывает по одной строке файла за раз.
- Пройти по байтам строки.
- На основе первого байта сохранить от одного до четырех байтов из строки в строку C с именем cStr.
- Немедленно добавьте cStr в конец cStrings, который представляет собой вектор const char *.
- Перейдите к следующему символу в строке, увеличив i в зависимости от количества только что добавленных байтов.
- Повторяйте этот процесс, пока вся строка не будет прочитана и преобразована.
- Добавьте cStrings в конец cStringVectors, который представляет собой вектор векторов const char *.
- Как только весь файл будет преобразован в пригодное для использования состояние, переходите к штампованию процесс.
- Процесс штамповки по существу представляет собой двумерный цикл, который передает одну cStr в addstr() за раз и помещает ее на экран.
Код: Выделить всё
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// the function requires the coordinates of the top left char in the file (x, y)
// then the length and height of the area in the file you want (length, height)
// then the coordinates you want the top left corner of the sprite to be placed on the screen (xpos, ypos)
// and finally the path to the file as a string (file)
void stamp(int x, int y, int length, int hight, int xpos, int ypos, string file) {
ifstream sprtfile(file);
string line;
move(ypos, xpos);
if (sprtfile.is_open()) {
// the file is read and then stores as a 3D vector
// each cstring is actually all the bytes required to be one utf-8 char
// so I can treat it as a 2D vector of chars
vector cStringVectors;
// this loop works one line of the file at a time
// and stores them in a 2d vector
// that stores the chars like cStringVectors except its only one line at a time instead of many
while (getline(sprtfile, line)) {
vector cStrings;
size_t i = 0;
int testvar = 0; //explained later
//this whole section gathers all the bytes of a utf-8 char into a cstring bundle called cStr
while (i < line.length()) {
unsigned char byte = static_cast(line[i]);
size_t charLength;
if ((byte & 0x80) == 0) {
charLength = 1; // 0xxxxxxx
} else if ((byte & 0xE0) == 0xC0) {
charLength = 2; // 110xxxxx
} else if ((byte & 0xF0) == 0xE0) {
charLength = 3; // 1110xxxx
} else if ((byte & 0xF8) == 0xF0) {
charLength = 4; // 11110xxx
} else {
charLength = 1; // Failsafe
}
// cStr works and it the proper char every time
string cStr = line.substr(i, charLength);
// in other examples you can use .push_back() to append vectors to vectors
cStrings.push_back(cStr.c_str());
// However, indexing cStrings to see whats in it have been the problem
addstr(cStrings[0]); // no matter what you set the index to, it doesn't seem to print that index
//ex: if you keep the index as 0 it should only ever print the first char in the line every how to time addstr() is called, instead every time you call it prints a new char
//the crazy part is if you set the index of cString to "testvar"
//it should have to print a new index each time,
//but instead it prints exactly the same thing as only using index zero!!!
testvar++;
refresh(); // ncurses function to display the new characters added to the screen
getch(); // pauses until it detects keyboard input so its easier to see each step playing out
i += charLength; // moves on to the next char in the line from the file
}
cStringVectors.push_back(cStrings); // should add that line to the larger 3d vector
}
// loops that should make sure only the selected portion of the file is stamped on the screen
for (size_t i=y; i < y+hight; i++) {
for (size_t j=x; j < x+length; j++) {
move(ypos+i-y, xpos+j-x); // moves to the proper location to add the char
getch(); // pauses until it detects keyboard input so its easier to see each step playing out
// this one acts different
// no matter what i or j is, it only adds the last char in the file
addstr(cStringVectors[i][j]);
}
}
sprtfile.close();
} else {
cerr
Подробнее здесь: [url]https://stackoverflow.com/questions/79859448/why-does-my-2d-vector-of-c-strings-not-output-the-element-at-the-given-index[/url]
Мобильная версия