提问人:jakarta_tea 提问时间:9/27/2023 最后编辑:jakarta_tea 更新时间:9/27/2023 访问量:78
将 int 类型写入文件并从同一文件读回字符串类型 (C++ i/o fstream)
Writing int type to a file and reading back string types from the same file (C++ i/o fstream)
问:
我目前正在学习用 C++ 编写和读取文件,我偶然发现了一些我不确定自己是否理解的东西。
我正在将 5 个不同的整数写入“ages.txt”文件,然后我使用一个函数读取该文件的内容并将其输出到控制台。我真正不明白的是,在写入文件时,我使用类型,并从中读回,我使用类型,并且仍然从“ages.txt”文件中正确读取数字。read_file()
int
string
这是否意味着在后台发生了一些转变?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void read_file()
{
ifstream file ("ages.txt");
vector<string> read_age;
string input;
while(file >> input)
{
read_age.push_back(input);
}
for(string age : read_age)
{
cout << age << endl;
}
}
int main()
{
ofstream file ("ages.txt");
if(file.is_open())
{
cout << "File was opened" << endl;
}
vector<int> ages;
ages.push_back(12);
ages.push_back(13);
ages.push_back(14);
ages.push_back(15);
ages.push_back(16);
for(int age : ages)
{
file << age << endl;
}
read_file();
return 0;
}
我尝试在函数中的任何位置将字符串更改为字符类型,然后控制台的输出如下(数据已在“ages.txt”文件中):read_file()
File was opened
1
2
1
3
1
4
1
5
1
6
答:
0赞
Cem Polat
9/27/2023
#1
您应该修改read_file函数以读取整数而不是字符串:
void read_file()
{
ifstream file("ages.txt");
vector<int> read_age;
int input;
while (file >> input)
{
read_age.push_back(input);
}
for (int age : read_age)
{
cout << age << endl;
}
}
评论
0赞
jakarta_tea
9/27/2023
嘿,感谢您的回答,我知道这一点,但我在这里是故意这样做的,因为这是我的第一个问题 - 我可以存储在我的“ages.txt”文件中,但是当尝试从中读取时,我可以使用类型,并且不会出错。int
string
1赞
john
9/27/2023
#2
是的,这确实意味着一些转换正在发生。
使用将您正在编写的任何内容转换为文本。文本是无类型的,数字序列可以是整数,也可以是字符串。同样,将您正在阅读的任何文本转换为某种类型。现在这里存在一个潜在的问题,因为某些文本无法转换为某些类型,但任何内容都可以作为字符串读取。<<
>>
评论
int
string