鱼C论坛

 找回密码
 立即注册
查看: 1047|回复: 1

[已解决]c++读取txt文件

[复制链接]
发表于 2022-2-26 23:13:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
c++读取txt文件,txt文件大概是五个字符串一行,然后差不多一百行,怎么读取,并且存入一个string类的二维数组。
最佳答案
2022-2-26 23:25:39
你这个问的就有点笼统...
那我就给你贴一段书本上讲文件IO的代码吧...

  1. // fileio.cpp -- saving to a file
  2. #include <iostream> // not needed for many systems
  3. #include <fstream>
  4. #include <string>

  5. int main()
  6. {
  7.     using namespace std;
  8.     string filename;

  9.     cout << "Enter name for new file: ";
  10.     cin >> filename;

  11. // create output stream object for new file and call it fout
  12.     ofstream fout(filename.c_str());

  13.     fout << "For your eyes only!\n";        // write to file
  14.     cout << "Enter your secret number: ";   // write to screen
  15.     float secret;
  16.     cin >> secret;
  17.     fout << "Your secret number is " << secret << endl;
  18.     fout.close();           // close file

  19. // create input stream object for new file and call it fin
  20.     ifstream fin(filename.c_str());
  21.     cout << "Here are the contents of " << filename << ":\n";
  22.     char ch;
  23.     while (fin.get(ch))     // read character from file and
  24.         cout << ch;         // write it to screen
  25.     cout << "Done\n";
  26.     fin.close();
  27.     // std::cin.get();
  28.     // std::cin.get();
  29.     return 0;
  30. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-2-26 23:25:39 | 显示全部楼层    本楼为最佳答案   
你这个问的就有点笼统...
那我就给你贴一段书本上讲文件IO的代码吧...

  1. // fileio.cpp -- saving to a file
  2. #include <iostream> // not needed for many systems
  3. #include <fstream>
  4. #include <string>

  5. int main()
  6. {
  7.     using namespace std;
  8.     string filename;

  9.     cout << "Enter name for new file: ";
  10.     cin >> filename;

  11. // create output stream object for new file and call it fout
  12.     ofstream fout(filename.c_str());

  13.     fout << "For your eyes only!\n";        // write to file
  14.     cout << "Enter your secret number: ";   // write to screen
  15.     float secret;
  16.     cin >> secret;
  17.     fout << "Your secret number is " << secret << endl;
  18.     fout.close();           // close file

  19. // create input stream object for new file and call it fin
  20.     ifstream fin(filename.c_str());
  21.     cout << "Here are the contents of " << filename << ":\n";
  22.     char ch;
  23.     while (fin.get(ch))     // read character from file and
  24.         cout << ch;         // write it to screen
  25.     cout << "Done\n";
  26.     fin.close();
  27.     // std::cin.get();
  28.     // std::cin.get();
  29.     return 0;
  30. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-25 01:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表