好的,需要一些帮助。我已经在一个文件中读到了一个数组。我需要采取数组并格式化它,以便格式化数字。文本文件只是一个数字列表。例如,我需要取前两个数字并对它们进行格式化,以便将它打印到控制台,如下所示:" 1-0"。到目前为止,这是我的代码。注意应该进行格式化的不完整函数。
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<fstream>
using namespace std;
string ArrayFormat(int array[]);
int main() {
const int ARRAY_SIZE = 21;
string filename;
ifstream inputfile;
int score[ARRAY_SIZE];
cout <<"\nPlease enter the name of a file: ";
cin >> filename;
inputfile.open(filename.c_str());
if (inputfile.fail()){
perror(filename.c_str());
exit(1);
}// end of error test
for (int i=0;i<20;i++){
inputfile >> score[i];
// cout << score[i] << endl;
}// end of for loop to read into array
inputfile.close();
}// end of main
string ArrayFormat(int array[]){
for(int i=0; i<=21; i++){
}
}// end of ArrayFormat
答案 0 :(得分:1)
for(int i = ; i < 21; i++)
{
if(i%2 == 1)
std::cout << "-" << array[i] << "\t";
else
std::cout << array[i];
}
这将以2对的形式打印数组,格式正确。
编辑:如果你需要打印出数字对,为什么数组是奇数?