【发布时间】:2016-12-09 09:29:08
【问题描述】:
Programm 创建两个文件。 当我在控制台中输入文本然后将其打印到文件中时,一切正常,但是当我阅读此文件时,处理文本(交换每个单词中的第一个和最后一个字母),然后在新文件中打印处理过的文本,我有:
文本T
罗夫
例子
去甲壳虫
而不是
字符串 1: 文本 rof 示例
字符串 2: gomethins
如何在新文件中像原始文件一样打印文本?
void create_file()
{
ofstream file_for_writing;
file_for_writing.open("file_w.txt");
const int n = 80;
int str_num = 0;
char ch1[n];
char sp[] = " ";
// cout << "Сколько строк вы желаете ввести? " << endl;
// cin >> str_num;
cout << "Введите, пожалуйста, текст: " << endl;
// cin.getline(ch1, n);
for (; ; )
{
/*
cin.get(ch1);
if (ch1 == '\n') continue;
else if (ch1 == ' ') break;
*/
gets_s(ch1);
// if (ch1[n-1] == '\n') continue;
if ( ! ch1[0] ) break;
file_for_writing << endl << ch1;
// cin.getline(sp, n);
}
system("pause");
// cin.getline(ch1, n);
cout << "Введенный текст:" << endl << ch1;
//
//while (strlen(ch1))
//{
// file_for_writing << ch1;
//}
}
void handle_file()
{
cout << "Меняем местами первую и последнюю буквы в словах: " << endl;
string s;
ifstream ifs("file_w.txt");
ofstream ofs;
ofs.open("handled.txt");
if (ifs.is_open())
{
s.assign((istreambuf_iterator<char>(ifs.rdbuf())), istreambuf_iterator<char>());
cout << "Оригинальный текст:" << endl;
cout << endl;
cout << s << endl;
cout << endl;
ifs.close();
}
stringstream ss(s);
cout << endl;
cout << endl;
cout << "Обработанный текст:" << endl;
cout << endl;
while (ss >> s) {
char chs[80];
swap(s.back(), s.front());
strcpy(chs, s.c_str());
cout << endl << chs;
ofs << endl << chs;
}
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(0, "RUS");
create_file();
system("cls");
handle_file();
_getch();
}
【问题讨论】:
-
如何不把所有的文本都放到字符串流中,而是把每一行,然后提取词,词处理,然后把处理后的行写入文件,如此一来文件中的所有行?
-
有人可以帮忙吗?