#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/