Programm创建两个文件。 当我在控制台中输入文本然后将其打印到文件时,一切正常,但当我正在读取此文件时,处理文本(在每个单词中交换第一个和最后一个字母)然后在新文件中打印处理文本,我'得到了:
文本
ROF
例如
gomethins
而不是
字符串1: 文字示例
字符串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();
}
答案 0 :(得分:0)
您提供的预期输出与实际输出相比,似乎指出这段代码是您问题的根源:
while (ss >> s) {
char chs[80];
swap(s.back(), s.front());
strcpy(chs, s.c_str());
cout << endl << chs;
ofs << endl << chs;
}
对于输出到文件的每个单词,您还要添加endl
,这就是为什么您将每个单词放在一个单独的行中,而不管它们在原始文件中的行分布。我建议你使用两个嵌套循环,一个读取内部另一个循环的行,处理该给定行中的每个单词。例如:
string line;
while (ss.getline(line)) {
stringstream line_stream(line);
while(line_stream >> s) {
char chs[80];
swap(s.back(), s.front());
strcpy(chs, s.c_str());
cout << chs;
ofs << chs;
}
cout << endl;
ofs << endl;
}
这是一个示例程序,它采用文件名并分别打印每一行:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main () {
using namespace std;
cout << "File name: ";
string file_name;
cin >> file_name;
// to open a file with an std::string as name you need c++11
ifstream file(file_name);
string line, word;
while (getline(file, line)) {
stringstream ss(line);
while (ss >> word) {
cout << word;
}
cout << "-- line --" << endl;
}
return 0;
}