在目录下建立myData.txt, 在其中输入:
1 2 3 4 5
6
7
执行下面程序:
- #include<iostream>
- #include<fstream>
- using namespace std;
-
- int main()
- {
- ifstream cin("myData.txt");
- int n;
- while(cin >> n)
- {
- cout << n << endl;
- }
-
- return 0;
- }
结果为:
1
2
3
4
5
6
7
看完上面的程序,我们再来欣赏一个小程序:
- #include<iostream>
- using namespace std;
-
- int main()
- {
- FILE *fp = fopen("myData.txt", "w");
- fprintf(fp, "1 2 \n3 4 5 6 \n"); // \n为换行
- fclose(fp);
-
- int a;
- fp = fopen("myData.txt", "r");
- while(EOF != fscanf(fp, "%d", &a))
- {
- cout << a << endl; // 读取文件中所有的整数
- }
- fclose(fp);
-
- return 0;
- }
结果为:
1
2
3
4
5
6