I want to traverse through each line. All I want to do is compare a user input of 4 numbers with each line of numbers from the file. If it matches the user wins.
Example of my text file
25 45 78 45
12 45 32 52
(I have over 100 lines in my text files, I will be adding more.)
In this file the position of 2, what is the position?
It's not an array, I can always put each line into a vector and clear it and move on to the next line.
This is not a homework problem, I just want to experience a "workplace database" type of code. Also I want to learn File I/O.
Keep checking and editing the text file.
#include <iostream>
#include <fstream>
int main() {
std::ifstream fin("filename");
int ua, ub, uc, ud;
std::cout << "Enter your four numbers: ";
std::cin >> ua >> ub >> uc >> ud;
int line = 0;
int a, b, c, d;
while (fin >> a >> b >> c >> d) {
++line;
if (a == ua && b == ub && c == uc && d == ud) {
std::cout << "Match on line " << line << '\n';
break; // if you only want the first match then break here
}
}
}
#include <iostream>
#include <fstream>
#include <algorithm>
int main() {
std::ifstream fin("filename");
int u[4];
std::cout << "Enter your four numbers: ";
std::cin >> u[0] >> u[1] >> u[2] >> u[3];
std::sort(&u[0], &u[4]);
int line = 0;
int f[4];
while (fin >> f[0] >> f[1] >> f[2] >> f[3]) {
std::sort(&f[0], &f[4]);
++line;
if (f[0] == u[0] && f[1] == u[1] && f[2] == u[2] && f[3] == u[3]) {
std::cout << "Match on line " << line << '\n';
break; // if you only want the first match then break here
}
}
}
If the order does matter and the maximum number is relatively small (the sample input suggests 2 digit numbers), then you could put the numbers into a bitset<100> and then compare - no sorting required.
However, with only 4 numbers, it's not clear if this would be faster. And it's certainly debatable whether it would be clearer code. That's up to you.