将 int 类型写入文件并从同一文件读回 string 类型(C++ i/o fstream)

问题描述 投票:0回答:1

我目前正在学习用 C++ 编写和读取文件,我偶然发现了一些我不确定我是否理解的内容。

我正在将 5 个不同的整数写入“ages.txt”文件,然后使用

read_file()
函数读取该文件的内容并将其输出到控制台。我真正不明白的是,当写入文件时,我使用的是
int
类型,从文件中读取时我使用的是
string
类型,并且仍然可以从“ages.txt”中正确读取数字“文件。

这是否意味着后台发生了一些转换?

#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;
}

我尝试在

read_file()
函数中将字符串更改为 char 类型,然后控制台的输出如下(数据已存在于“ages.txt”文件中):

File was opened
1
2
1
3
1
4
1
5
1
6
c++ fstream
1个回答
0
投票

您的输入和输出向量类型不匹配。只需将 read_age 更新为整数向量即可。

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.