c++读取用户输入名称的txt文件
时间: 2023-08-16 14:07:16 浏览: 53
你可以使用C++的文件输入流来读取用户输入的名称的txt文件。以下是一个基本的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
cout << "请输入要读取的文件名:";
cin >> filename;
ifstream infile(filename.c_str()); // 打开文件
if (!infile.is_open()) { // 判断文件是否打开成功
cout << "文件打开失败!" << endl;
return 1;
}
string line;
while (getline(infile, line)) { // 读取文件内容
cout << line << endl;
}
infile.close(); // 关闭文件
return 0;
}
```
在这个例子中,程序会要求用户输入要读取的文件名,然后通过文件输入流打开该文件并读取其中的内容,最后关闭文件。注意,我们需要使用`c_str()`函数将`string`类型的文件名转换成`const char*`类型的文件名,以便`ifstream`对象能够正确打开文件。
相关问题
vs2017 c++读取TXT文档内容写入到新建TXT文档
以下是在 VS2017 中使用 C++ 读取 TXT 文档内容并写入到新建 TXT 文档的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string input_file = "input.txt";
std::string output_file = "output.txt";
// 打开输入文件
std::ifstream fin(input_file);
// 检查输入文件是否打开成功
if (!fin.is_open())
{
std::cerr << "Failed to open input file: " << input_file << std::endl;
return 1;
}
// 打开输出文件
std::ofstream fout(output_file);
// 检查输出文件是否打开成功
if (!fout.is_open())
{
std::cerr << "Failed to open output file: " << output_file << std::endl;
return 1;
}
// 逐行读取输入文件并写入输出文件
std::string line;
while (std::getline(fin, line))
{
fout << line << std::endl;
}
// 关闭文件流
fin.close();
fout.close();
std::cout << "File copied successfully!" << std::endl;
return 0;
}
```
在这个示例程序中,我们首先定义了输入文件和输出文件的位置,然后打开输入和输出文件。接着,我们使用 `std::getline` 函数逐行读取输入文件,并将每一行写入到输出文件中。最后,我们关闭文件流,并输出成功消息。
你可以根据自己的需要修改输入和输出文件的位置和名称。请注意,在使用 Visual Studio 编译器时,你需要确保输入文件和输出文件位于程序所在的目录中,或者使用绝对路径来指定文件位置。
可以读取txt文件吗
可以的,你可以使用C++的文件流来读取txt文件。以下是简单的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
if (file.is_open()) { // 检查文件是否成功打开
std::string line;
while (std::getline(file, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出每一行内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std::endl;
}
return 0;
}
```
在上面的示例中,我们使用`std::ifstream`来创建一个输入文件流对象,并通过`open`函数打开名为"example.txt"的文件。然后,我们使用`std::getline`函数逐行读取文件内容,并将每一行输出到控制台。最后,我们使用`close`函数关闭文件。
请注意,上述代码中的文件名"example.txt"是一个示例,你需要根据实际情况替换为你要读取的txt文件的路径和名称。