将文件中的数据读出来c++
时间: 2023-06-25 11:02:47 浏览: 82
读取文件中的数据可以使用 C++ 标准库中的 ifstream 类。以下是一个示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("data.txt"); // 打开文件
string line;
while (getline(infile, line)) { // 逐行读取文件
cout << line << endl; // 输出每行数据
}
infile.close(); // 关闭文件
return 0;
}
```
以上代码中,我们打开一个名为 `data.txt` 的文件,逐行读取文件中的数据,并将每行数据输出到控制台。最后,记得关闭文件。
相关问题
将文件中的数据用string读出来c++
可以使用C++的文件输入流(ifstream)和字符串流(stringstream)来读取文件中的数据并存储到字符串中。假设文件名为data.txt,以下是示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
std::ifstream file("data.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string data = buffer.str();
std::cout << data << std::endl;
return 0;
}
```
首先,我们创建一个文件输入流对象file,并打开要读取的文件data.txt。然后,我们创建一个字符串流对象buffer,并使用file.rdbuf()将文件中的数据读入到buffer中。最后,我们将buffer中的数据转换为字符串类型并存储到data变量中。可以使用std::cout输出data来验证读取是否成功。
C++将文件中的数据读入栈中
好的,以下是使用C++将文件中的数据读入栈中的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int main()
{
// 打开文件并读取其中的数据
ifstream inputFile("data.txt");
string line;
stack<string> myStack;
if (inputFile.is_open())
{
while (getline(inputFile, line))
{
// 将读取的数据逐个压入栈中
myStack.push(line);
}
inputFile.close();
}
// 输出栈中的数据
while (!myStack.empty())
{
cout << myStack.top() << endl;
myStack.pop();
}
return 0;
}
```
在这个例子中,我们使用了C++的 `ifstream` 类来打开文件,使用 `getline()` 方法读取文件中的每一行数据,并将其压入栈中。最后,我们使用 `stack` 的 `top()` 和 `pop()` 方法输出栈中的数据。
需要注意的是,文件读取完成后应该关闭文件,这里使用了 `ifstream` 的 `close()` 方法来关闭文件。