C++ txt文本是否完成读的判断及文件内容的输出(Example)

``文本内容

在这里插入图片描述

读取目标:x 300 y 200 z 100

文件位置:“桌面\1.txt"

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<stdio.h>
using namespace std;
vector<string> &Labelnameinput(fstream &file,vector<string> & array)
{
 string temp; 
 while(!file.eof())
 {
  file>>temp;
  array.push_back(temp);
 }
 return array;
}

要点:
1.eof()
2.push_back()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中可以使用`fstream`库来进行文件写操作。具体的操作如下: #### 写文件 ```c++ #include <fstream> #include <iostream> using namespace std; int main() { ofstream file("example.txt"); // 创建一个名为example.txt文件 if (!file.is_open()) { // 判断文件是否打开成功 cout << "无法创建文件" << endl; return 1; } file << "Hello, World!"; // 向文件中写入数据 file.close(); // 关闭文件 return 0; } ``` 在上面的示例代码中,我们使用`ofstream`类创建了一个名为example.txt文件,并向文件中写入了一行文本。最后,我们关闭了文件。 #### 文件 ```c++ #include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream file("example.txt"); // 打开一个名为example.txt文件 if (!file.is_open()) { // 判断文件是否打开成功 cout << "无法打开文件" << endl; return 1; } string line; while (getline(file, line)) { // 文件中的每一行 cout << line << endl; // 输出每一行内容 } file.close(); // 关闭文件 return 0; } ``` 在上面的示例代码中,我们使用`ifstream`类打开了一个名为example.txt文件,并使用`getline()`函数逐行文件中的内容。最后,我们关闭了文件。 #### 判断文件完 在文件取时,可以使用`eof()`函数来判断文件是否取到了文件末尾。`eof()`函数会在文件取到文件末尾时返回true,否则返回false。下面是一个示例代码: ```c++ #include <fstream> #include <iostream> using namespace std; int main() { ifstream file("example.txt"); // 打开文件 if (!file.is_open()) { // 判断文件是否打开成功 cout << "无法打开文件" << endl; return 1; } char c; while (!file.eof()) { // 判断是否取到文件末尾 file.get(c); // 取一个字符 cout << c; // 输出字符 } file.close(); // 关闭文件 return 0; } ``` 在上面的示例代码中,我们使用`eof()`函数来判断文件是否取到了文件末尾。如果取到了文件末尾,循环就会结束,否则就会继续文件内容

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值