c++根据输入读入文件
时间: 2023-08-03 20:58:09 浏览: 60
在C++中,你可以使用流对象和文件流操作符来读取文件。以下是一个示例代码,演示如何根据输入读取文件:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::string filename;
std::cout << "请输入文件名:";
std::cin >> filename;
std::ifstream file(filename);
if (!file) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
```
这个程序首先要求用户输入文件名,然后尝试打开该文件。如果文件无法打开,程序将输出错误信息并退出。如果文件成功打开,程序将逐行读取文件内容并将其输出到控制台。
注意:在使用文件流之后,不要忘记调用`close()`方法关闭文件,以确保资源的正确释放。
相关问题
c++输入文件名打开文件
可以使用`fstream`库来打开和读取文件。
以下是一个示例代码,以打开一个文本文件为例:
```c++
#include <iostream>
#include <fstream>
int main()
{
std::string filename;
std::cout << "请输入文件名:";
std::cin >> filename;
std::ifstream file(filename);
if (!file.is_open())
{
std::cout << "无法打开文件!" << std::endl;
return -1;
}
// 读取文件内容
std::string line;
while (std::getline(file, line))
{
std::cout << line << std::endl;
}
// 关闭文件
file.close();
return 0;
}
```
在这个示例中,首先要求用户输入文件名,然后使用`std::ifstream`打开文件。如果文件打开失败,则输出错误信息并返回-1。如果成功打开文件,则可以使用`std::getline`函数从文件中读取一行内容,并输出到控制台。最后,使用`close()`函数关闭文件。
注意,在使用`fstream`库时,需要包含头文件`<fstream>`。
c++打开文件修改文件输入输出流
以下是一个简单的C++例子,演示如何打开、更改和输入输出文件:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main () {
// 打开文件
ofstream outfile;
outfile.open("example.txt");
// 写入数据到文件
outfile << "This is a line." << endl;
outfile << "This is another line." << endl;
// 关闭文件
outfile.close();
// 读取文件
ifstream infile;
infile.open("example.txt");
string line;
while (getline(infile, line)) {
cout << line << endl;
}
// 关闭文件
infile.close();
return 0;
}
```
在这个例子中,我们使用了`ofstream`和`ifstream`类来打开文件进行写入和读取。我们首先使用`ofstream`类打开文件,然后使用`<<`运算符将数据写入文件。最后,我们使用`close()`函数关闭文件。接着,我们使用`ifstream`类打开文件进行读取,并使用`getline()`函数逐行读取文件内容。最后,我们再次使用`close()`函数关闭文件。