c++file写入名字和电话号码
时间: 2024-05-06 19:18:42 浏览: 11
你可以使用C++的文件输入输出流来实现这个任务。以下是一个简单的示例代码,可以用来将名字和电话号码写入文件:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name, phone;
ofstream outfile("contacts.txt"); // 创建输出文件流对象
// 获取用户输入的名字和电话号码
cout << "Enter name: ";
getline(cin, name);
cout << "Enter phone number: ";
getline(cin, phone);
// 将名字和电话号码写入文件
outfile << name << " " << phone << endl;
// 关闭文件流对象
outfile.close();
return 0;
}
```
在这个示例中,我们首先创建了一个名为“contacts.txt”的输出文件流对象。然后,使用getline函数获取用户输入的名字和电话号码,并将它们写入文件中。最后,我们关闭了文件流对象。
请注意,如果文件不存在,则会自动创建该文件。如果文件已经存在,则文件中的任何现有内容都将被覆盖。
相关问题
c++文件的读取和写入
C++中文件的读取和写入可以通过文件流来实现,具体可以使用fstream库中的ifstream和ofstream类来分别进行文件的读取和写入。
以下是一个简单的例子,演示如何读取一个文本文件并输出到控制台:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "example.txt";
ifstream infile(filename);
if (infile.is_open()) {
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
} else {
cout << "Unable to open file " << filename << endl;
}
return 0;
}
```
以下是一个简单的例子,演示如何将一些文本写入到一个文件中:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "example.txt";
ofstream outfile(filename);
if (outfile.is_open()) {
outfile << "Hello World!\n";
outfile << "This is a text file.\n";
outfile.close();
} else {
cout << "Unable to create file " << filename << endl;
}
return 0;
}
```
需要注意的是,当写入文件时,如果文件不存在,则会创建一个新文件。如果文件已经存在,则会删除原有内容并写入新的内容。
c++读取和写入txt
文件的Python代码示例:
读取txt文件:
```python
with open("file.txt", "r") as f:
content = f.read()
print(content)
```
上面的代码使用了`with open`语句打开文件,指定文件名为`file.txt`,并使用`r`模式读取文件。读取的内容被保存在`content`变量中,并使用`print`函数输出。
写入txt文件:
```python
with open("file.txt", "w") as f:
f.write("Hello, world!")
```
上面的代码使用了`with open`语句打开文件,指定文件名为`file.txt`,并使用`w`模式写入文件。写入的内容为`Hello, world!`。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)