Chương trình dưới đây chạy để cắt file thành các đoạn 100 kí tự sao cho kí tự thứ 100, 200, 300… là khoảng trắng, tránh việc cắt vào 1 từ đầy đủ. Chương trình làm việc rất tốt với file chứa văn bảng tiếng anh, nhưng khi file là tiếng việt thì nó sẽ bỏ qua những chữ không thuộc ASCII vì char không support tiếng việt. Sau hơn nửa ngày tìm hiểu thì mình tìm ra cách là sử dụng thư viện codecvt, wchar_t thay cho char, wscanf thay scanf nhưng vẫn chưa đc. Mong mọi người giúp đỡ!
Đây là bài mình sửa: https://onlinegdb.com/DYONdDiMQ
#include <stdio.h>
#include <iostream>
#include <cwchar>
#include <fcntl.h> //_O_WTEXT
#include <io.h> //_setmode()
#include <string>
#include <locale>
#include <codecvt> //possible C++11?
#include <fstream>
const int GAP = 100;
int main() {
_setmode(_fileno(stdin), _O_WTEXT); //needed for input
_setmode(_fileno(stdout), _O_WTEXT); //needed for output
_wfreopen(L"iput.txt", L"rt", stdin);
_wfreopen(L"oput.txt", L"wt", stdout);
int cnt = 0;
wchar_t str[2002];
wchar_t c;
int i, len;
while (wscanf(L"%c", &c) != -1) {
str[cnt] = c;
cnt++;
if (cnt % GAP == 0) {
if (str[cnt - 1] == ' ') continue;
len = 1; // number of space will be added
while (len < GAP && str[cnt - 1 - len] != ' ')
len++;
if (len == GAP) continue;
// move len character forward, start from cnt - len
for (i = cnt - len; i < cnt; i++) {
str[i + len] = str[i];
str[i] = ' ';
}
cnt += len;
}
}
str[cnt] = 0;
wprintf(L"%s", str);
return 0;
}
Code gốc: https://onlinegdb.com/HlYta0snc
#include <stdio.h>
const int GAP = 100;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int cnt = 0;
char str[2002];
char c;
int i, len;
while (scanf("%c", &c) != -1) {
str[cnt] = c;
cnt++;
if (cnt % GAP == 0) {
if (str[cnt - 1] == ' ') continue;
len = 1; // number of space will be added
while (len < GAP && str[cnt - 1 - len] != ' ')
len++;
if (len == GAP) continue;
// move len character forward, start from cnt - len
for (i = cnt - len; i < cnt; i++) {
str[i + len] = str[i];
str[i] = ' ';
}
cnt += len;
}
}
str[cnt] = 0;
printf("%s", str);
return 0;
}