c++ - 使用计数器数组从文件中提取整数并计算响应数?

标签 c++ arrays file-io

#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

void addRecordstoFile();
void readRecordsFromFile();

int main(){


    addRecordstoFile();
    readRecordsFromFile();
}

void addRecordstoFile(){

这会将整数添加到文件中,但我希望它退出时(当用户输入 -1 时)不显示在 .txt 文件中

    int num=1;
    char response;

    ofstream outFile("numbers.txt",ios::out);

    if (!outFile){
        cerr<<"File was not opened correctly"<<endl;
        exit(1);
    }

    cout<<"\t\t\tSurvey Response Analyzer"<<endl;


    while(num!=-1){

            cout<<"\n Enter a survey response from 1 to 10 (-1 to end): ";
            cin>>num;


            if(num<1 || num>10){
                cout<<"\n Please enter a valid response from (1-10): ";
                cin >>num;

            }

            outFile << num <<" ";

    }

            outFile.close();
            cout<<"Saved to file..."<<endl;
            system("pause");
}

这是主要问题所在,我应该从文本文件中提取整数并将它们放在一个计数器数组中以计算用户输入 1 到 10 之间的数字的次数。我完全迷路了,因为我需要数组的大小来确定我的循环。

    void readRecordsFromFile(){

    ifstream inFile("numbers.txt",ios::in);

    if(!inFile){
        cerr<<"File was not found";
        exit (1);
    }

如何在不知道文本文件中数组大小的情况下在这里创建一个计数器数组?

最佳答案

<强>1。第一次查询:

This adds the integers to the file but I want when it exits (when the user enters -1) not be displayed in the .txt file

替换

if (num < 1 || num > 10) {
    cout<<"\n Please enter a valid response from (1-10): ";
    cin >>num;
}
outFile << num <<" ";

if (num < 1 || num > 10) {
    cout<<"\n Please enter a valid response from (1-10): ";
    cin >>num;
} else {
    outFile << num <<" ";
}

<强>2。第二个查询:

I would need the size of the array to determine my loop

不,你不知道。您可以使用 while 循环来检查结束。

关于c++ - 使用计数器数组从文件中提取整数并计算响应数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22764177/

相关文章:

c++ - 如何确定代码在内核空间中花费大量时间的位置(系统调用)

java - 2048 游戏的随机单元格中的随机数

java - 我知道 Java 不支持泛型数组,但我不知道如何解决这个问题,以便它可以工作

python - 如何在python中使用print语句测试文件写入

Python:如何使用 Python 访问 mp3 文件的元数据?

c++ - 推断 operator+ 和其他运算符的(模板化)返回类型

c++ - 我如何搜索这个问题(范围内的宏与内联函数)

javascript - 我只能返回 1 个数组

c++ - 在C++中写入输入和输出文件

c++ - 平衡二叉树编码