Bài tập (code mẫu: NhapXuatFile) Đọc từ file “input.txt” mảng một chiều các số thực. Tập…
- User
Bài tập (code mẫu: NhapXuatFile) Đọc từ file “input.txt” mảng một chiều các số thực. Tập tin input.txt có nội dung như sau: Dòng đầu chứa 1 số nguyên là số lượng phần tử của mảng Dòng sau chứa các phần tử của mảng cách nhau bởi khoảng trắng Ví dụ: 5 1.2 2.3 3.4 4.5 5.6
#include <stdio.h>
void XuatFile(char* tenFile, float* arr, int n) { //mo file de ghi FILE* fo = fopen(tenFile, "wt"); // wt = write (ghi) + text (dang van ban)
//ghi du lieu ra file for (int i = 0; i < n; i++) fprintf(fo, "%0.1f ", arr[i]);code// dong file fclose(fo);}
void main() { // mo file de doc FILE* fi = fopen("input.txt", "rt");code//doc du lieu int n; fscanf(fi, "%d", &n); float* arr = new float[n]; for (int i = 0; i < n; i++) fscanf(fi, "%f", &arr[i]); //dong file fclose(fi); // in ra man hinh de kiem tra for (int i = 0; i < n; i++) printf("%0.1f ", arr[i]); printf("\n"); // xuat ra file XuatFile("output.txt", arr, n);}
Tạo tập tin dữ liệu mới “MSSV.txt” thay cho file “input.txt”. Nhập dữ liệu cho file MSSV.txt và chạy chương trình.
Assistant
Đã hiểu ý bạn muốn nói. Đây là mã nguồn để tạo file "MSSV.txt" với cấu trúc như bạn mô tả.
c++#include <iostream> using namespace std; void NhapFile(char* tenFile, int& n, int* arr) { // mo file de doc FILE* fi = fopen(tenFile, "rt"); // doc du lieu fscanf(fi, "%d", &n); for (int i = 0; i < n; i++) fscanf(fi, "%d", &arr[i]); // dong file fclose(fi); } int main() { const int MAX = 100; int n; int arr[MAX]; NhapFile("input.txt", n, arr); // mo file de ghi FILE* fo = fopen("MSSV.txt", "wt"); // wt = write (ghi) + text (dang van ban) // ghi du lieu ra file fprintf(fo, "%d\n", n); for (int i = 0; i < n; i++) fprintf(fo, "%d ", arr[i]); // dong file fclose(fo); return 0; }Bạn có thể copy mã nguồn này vào file của mình và chạy để tạo file "MSSV.txt" theo yêu cầu. File này sẽ có dòng đầu chứa số lượng phần tử và các dòng tiếp theo chứa các phần tử của mảng, cách nhau bởi khoảng trắng.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.