【发布时间】:2018-12-12 10:37:30
【问题描述】:
我收到了未知数量的“宽符号”。文本被格式化为句子,我必须将其添加到结构“文本”中。
这些是我的结构:
struct Sentence {
wchar_t *sentence;
int amount_of_symbols;
};
struct Text {
struct Sentence *sentences;
int amount_of_sentences;
};
我为“句子”结构的数组动态分配内存并添加它们。 这是我的输入代码:
int amount_of_sentences = 0;
struct Sentence *sentences = (struct Sentence *) malloc(amount_of_sentences * sizeof(struct Sentence));
struct Text text = {sentences, amount_of_sentences};
wchar_t symbol;
int buffer_size = 0;
wchar_t *buffer = (wchar_t *) malloc(buffer_size * sizeof(wchar_t));
bool sentence_begun = true;
while (true) {
symbol = getwchar();
if (symbol == '\n')
break;
if (sentence_begun && symbol == ' ') {
sentence_begun = false;
continue;
}
buffer = (wchar_t *) realloc(buffer, (++buffer_size) * sizeof(wchar_t));
buffer[buffer_size - 1] = symbol;
if (symbol == '.') {
buffer[buffer_size] = '\0';
text.amount_of_sentences++;
text.sentences = (struct Sentence *) realloc(text.sentences, text.amount_of_sentences * sizeof(struct Sentence));
text.sentences[text.amount_of_sentences - 1].amount_of_symbols = buffer_size;
text.sentences[text.amount_of_sentences - 1].sentence = (wchar_t *) malloc(buffer_size * sizeof(wchar_t));
text.sentences[text.amount_of_sentences - 1].sentence = buffer;
buffer_size = 0;
buffer = (wchar_t *) realloc(buffer, buffer_size * sizeof(wchar_t));
sentence_begun = true;
}
}
一切似乎都很好,但是当我尝试输出我的所有句子时,并不是所有的句子都显示出来,并且有些重复。
这是我的输出代码:
for (int i = 0; i < text.amount_of_sentences; i++) {
wprintf(L"%ls\n", text.sentences[i].sentence);
}
输入输出示例:
adjsand. asdad.a.a. aaaa. adsa.
a.
adsa.
adsa.
这段代码有什么问题,我应该改变什么?
【问题讨论】:
-
您能否说明
text和sentence_begun是如何声明和初始化的? -
@Schwern, int amount_of_sentences = 0; struct Sentence *sentences = (struct Sentence *) malloc(amount_of_sentences * sizeof(struct Sentence)); struct Text text = {sentences, amount_of_sentences}; bool sentence_begun = true;
-
Please edit your question 这样代码示例就更完整了。
-
@Schwern,修改完毕
标签: c struct malloc realloc wchar-t