任务:(一些比较程序的乐透)用户输入7个数字(从1到39),并将这些数字与文本文件中的每一行(7个数字)进行比较。
如果用户输入(7个数字)在任何一行中匹配超过3次,则应该在底部说它不合适。
示例: 文本文件:
2,5,8,16,25,27,32
1,4,15,19,22,25,36
7,12,13,27,35,38,39
。 。
程序中的用户输入:
1,5,16,21,25,32,36
现在程序应显示:
2,5,8,16,25,27,32匹配:4
1,4,15,19,22,25,36匹配:3
7,12,13,27,35,38,39匹配:0
。 。
有超过3场比赛!
现在我的代码是这样的(但它只检查第一行并在所有行中显示相同数量的匹配):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <ctime>
using namespace std;
int main () {
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int z=0;
int rezultati;
while (z!=1) {
cout<<"Title of the program"<<endl;
//Odpri txt
string line;
ifstream myfile ("stevilke.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
line=rezultati;
}
myfile.close();
}
else cout << "Unable to open file";
//Glavni prog:
cout<<"Napisi stevilke (1 enter 2 enter 3 enter ...)"<<endl;
cin>>a>>b>>c>>d>>e>>f>>g;
if (a>0 && a<40 && b>0 && b<40 && c>0 && c<40 && d>0 && d<40 && f>0 && f<40 && g>0 && g<40){
// preveri enake
string line;
ifstream myfile ("stevilke.txt");
while (getline (myfile,line)){
//računam numom
const int n = 7 ;
std::srand( std::time(0) ) ;
int lottoresults [39] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39} ;
for( int i = 0 ; i < n ; ++i );
// numbers entered by the user
int userinput[n] = { a, b, c, d, e, f, g } ;
for( int i = 0 ; i < n ; ++i );
// check for matching numbers
int cnt_matches = 0 ; // #matches
for( int i = 0 ; i < n ; ++i ) // for each number entered by the user
{
const int user_num = userinput[i] ;
// check if the number entered by the user is a winning number
// (could use std::find() instead of writing a loop of out own)
for( int j = 0 ; j < n ; ++j ) // for each winning number
{
if( user_num == lottoresults[j] ) // is it the same as user_num?
{
// yes, we got a match
++cnt_matches ;
std::cout << a<<"," << b<<"," << c<<","<< d <<","<< e <<","<< f <<","<< g <<".";
}
}
}
std::cout << "Ujemanja : " << cnt_matches << '\n' ; //TUKI ! --- cnt_matches je v vsaki vrsti enak, spremenit da se spreminja za usako vrsto!
// numom do tu
cout << line <<'\n';
}
//Piši v txt
/*std::ofstream ofs;
ofs.open ("stevilke.txt", std::ofstream::out | std::ofstream::app);
ofs <<endl;
ofs <<a<<","<<b<<","<<c<<","<<d<<","<<e<<","<<f<<","<<g;
ofs.close(); */
cout<<"pritisni 1 za ponovitev programa, karkoli drugega program zapre."<<endl;
}
//konc if-a
else
cout<<"Dej se ne zajebavi no.. vpis prave stevilke"<<endl;
cout<<"Se enkrat zazeni program."<<endl;
system("pause");
}
return 0;
}
很抱歉很长时间的问题,但我已经解决了这个问题3晚了,我无法解决它... 我只是一个c ++的初学者,我真的很高兴你可以给我任何帮助!
也很抱歉我的英语不好(不是原生的)。
如果您需要更多信息或代码或任何内容,请告知我们。 谢谢!