C++读取txt文件(VS)
时间: 2023-07-11 08:23:04 浏览: 55
在VS中,可以使用以下代码读取txt文件:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "example.txt";
std::ifstream file(filename);
std::string line;
if (file.is_open())
{
while (getline(file, line))
{
std::cout << line << std::endl;
}
file.close();
}
else
{
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
```
其中,`filename`为要读取的txt文件名,`std::ifstream`用于打开文件,`getline()`函数读取文件中的一行,`file.close()`用于关闭文件。
相关问题
c++读取txt文件数据
以下是使用C++读取txt文件数据的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
std::string line;
if (file.is_open()) {
while (getline(file, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出每行内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
```
这段代码首先使用`ifstream`类打开名为"example.txt"的文件。然后,使用`getline`函数逐行读取文件内容,并将每行内容存储在`line`字符串中。最后,通过`cout`语句将每行内容输出到控制台。如果无法打开文件,则会输出"无法打开文件"。
c++ 读取txt文件
可以使用C++中的fstream库来读取txt文件,并将其存入string中。具体步骤如下:
1. 引入头文件
```c++
#include <fstream>
#include <string>
```
2. 打开文件
```c++
std::ifstream file("filename.txt");
```
3. 读取文件内容
```c++
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
```
4. 关闭文件
```c++
file.close();
```
完整代码如下:
```c++
#include <fstream>
#include <string>
int main() {
std::ifstream file("filename.txt");
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
return ;
}
```