以下程序完成功能:将data.txt文件的所有行加上行号后写到newdata.txt文件中。请将其补充完整。 #include <fstream.h> void main()…
- User
以下程序完成功能:将data.txt文件的所有行加上行号后写到newdata.txt文件中。请将其补充完整。 #include <fstream.h> void main() { int i=0; char line[100]; (1)__ ofstream outfile; (2)__ outfile.open("newdata.txt",ios::out); while(!infile.eof()) { (3)__ i++; (4)__ outfile<<line<<endl; } infile.close(); outfile.close(); }
- Assistant
#include #include using namespace std; int main() { int i=0; char line[100]; ifstream infile; infile.open("data.txt", ios::in); ofstream outfile; outfile.open("newdata.txt",ios::out); while(!infile.eof()) { infile.getline(line, 100); i++; outfile<<i<<". "<<line<<endl; } infile.close(); outfile.close(); return 0; }
- User
Test1.txt中包含一个整数序列为 8 39 67 44 3 55 62 20 -1 下面程序的运行结果是________。 #include #include using namespace std; int main() { int b; ifstream infile; infile.open("Test1.txt"); infile>>b; while(b>=0) { if(b%2==0) cout<<b<<','; infile>>b; } infile.close(); return 0; }
- Assistant
输出结果为:8,44,62,20,
- User
编写程序实现如下功能,读取文件”test.txt”里的内容,统计内容中数字的个数,将统计结果写入到文件“count.txt”中。
- Assistant
实现代码如下:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { int num_count = 0; char ch; ifstream infile("test.txt", ios::in); // 以读入方式打开 test.txt if (!infile.is_open()) // 判断文件是否打开成功 { cout << "无法打开文件 test.txt " << endl; return 1; } while (infile.get(ch)) // 逐个读取 test.txt 的每个字符 { if (isdigit(ch)) // 如果ch是数字 { num_count++; // 统计数字的个数 } } infile.close(); // 关闭文件 ofstream outfile("count.txt", ios::out); // 以写出方式打开 count.txt if (!outfile.is_open()) // 判断文件是否打开成功 { cout << "无法打开文件 count.txt " << endl; return 1; } outfile << "数字个数:" << num_count << endl; // 将数字个数写入 count.txt outfile.close(); // 关闭文件 return 0; }