从.txt文件将整数存储和读取到向量数组中

时间:2018-08-11 18:48:46

标签: c++ file vector

我的代码目标是创建一个整数值向量数组,将其存储到文本文件中,然后从文本文件中检索出来,再存储回向量数组中并打印到屏幕上。

到目前为止,我已经设法将值存储到文本文件中,但没有检索到它们。 构建消息的状态为“警告:ISO C ++禁止将字符串常量转换为'char *'[-Wwrite-strings]”。

如果我尝试运行代码,则应用程序崩溃。如果您能够将我的错误通知我并解释崩溃的原因,非常感谢。

IDE:代码块

代码:

#include <iostream>
#include <cstring>
#include <vector>
#include <fstream>
#include <stdio.h>

using namespace std;


int main() {
    FILE * fp;
    fp = fopen("sample.txt","w");
    if(fp == NULL) {
        cout << "[!] Cannot open file.";
        return(0);
    }
    vector<int> numArray;
    numArray.push_back(1);
    numArray.push_back(2);
    numArray.push_back(3);

    for(unsigned int x=0; x < numArray.size(); x++) {
        fprintf(fp, "%d ", numArray[x]);
    }

    numArray.clear();
    fclose(fp);

    FILE * fp2;
    fp2 = fopen("sample.txt","r");
    if(fp2 == NULL) {
        cout << "[!] Cannot open file.";
        return(0);
    }
    for(unsigned int x=0; !(feof(fp2)); x++) {
        fgets("%d", numArray[x], fp2);  //WARNING OCCURS HERE
    }

    fclose(fp);

    cout << "Vector: ";
    for(unsigned int x=0; x < numArray.size(); x++) {
        cout << numArray[x] << " ";
    }

    cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

切勿同时使用stdioiostream。 对于文件,最好使用fstream,如下所示:

#include <fstream>

ifstream fin("sample.txt");

int number;

while(fin >> number)
{
    numArray.push_back(number);
}

混合C和C ++标准函数会导致令人讨厌的事情的发生,这是一种不好的做法。