C++ Compare user input with each line in .txt file - c++

The task: (somekind of a lotto comparing program) User inputs 7 numbers (from 1 to 39) and those numbers are compared to each line (of 7 numbers) in a text file.
if the user input (7 numbers) matches more than 3 times in any of the lines, it should say at the bottom that it's not ok.
Example:
Text file:
2,5,8,16,25,27,32
1,4,15,19,22,25,36
7,12,13,27,35,38,39
.
.
.
User input in the program:
1,5,16,21,25,32,36
Now the program should display:
2,5,8,16,25,27,32 matches: 4
1,4,15,19,22,25,36 matches: 3
7,12,13,27,35,38,39 matches: 0
.
.
.
There are more than 3 matches!
For now my code is this (but it only checks the first line and displayes the same amount of matches in all lines):
#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;
}
Sorry for long question, but I'm struggeling with this problem for 3 nights already and I can't solve it...
I'm just a begginer in c++ and I'd really appriciate ANY help you could give me!
Also sorry for my bad english (not native).
If you need any more informations or code or anything, please let me know.
Thank you!

Related

How do I copy numbers from one text file to another but make them the next number?

I need to copy numbers from one text file and input them in another but make them the next number for example 1->2 3->4 ... 9->0
I have gotten the copying part down but cant figure out how to make one number the next.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");
string content = "";`
int i;`
for(i=0 ; infile.eof()!=true ; i++) // takes content
content += infile.get();
i--;
content.erase(content.end()-1); // erase last character
cout << i << " characters read...\n";
infile.close();
outfile << content; // output
outfile.close();
return 0;
}
I enter 1 2 3 4 5 and expect the output to be 2 3 4 5 6
You can check if an input char is a digit, then increase it, something like:
for (i = 0; infile.eof() != true; i++)// takes content
{
char currentChar = infile.get();
if (isdigit(currentChar))
{
currentChar++;
}
content += currentChar;
}
Expanding on the answer from Oded Radi,
If you want 9 to become 0 (as you described) you need to handle that, this is one way:
for (i = 0; infile.eof() != true; i++) // takes content
{
char currentChar = infile.get();
if (isdigit(currentChar))
{
currentChar = (((currentChar - '0') + 1) % 10) + '0';
}
content += currentChar;
}
If your input is separated by whitespace, your loop can be simple:
int value;
while (input_file >> value)
{
value = value + 1;
output_file << value << " ";
}
Another loop could be:
int value;
while (input_file >> value)
{
value = (value + 1) % 10;
output << value << " ";
}
The above loop restricts the numbers from 0 to 9.

C++: How to output a string two letters at a time?

I am trying to read from a file that contains sentences and output them two letters at a time.
IE:
>hello world
Output:
he ll ow or ld
Here is what I have.
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
int main()
{
string input;
ifstream infile;
infile.open("wordpairs.txt");
while(!infile.eof())
{
getline(infile, input);
for(int i = 0; i < input.length(); i++) //accidentally posted wrong code last time. My apologies.
{
cout << input[i] << input[i+1] << " ";
}
cout << endl;
}
infile.close();
return 0;
}
Edit & Run
and this is what it currently outputs for lets say for example, "hello world"
output:
h he el ll lo ow eo or rl ld d
How do I fix it? I figure it has something to do with my for loop calling input[i + 1], but i dont know how to combine words other than doing that.
This will print anything in pairs of 2 letters:
#include <iostream>
int main()
{
std::string input = "lo zpxcpzx zxpc pzx cpxz c lol";
for (size_t i = 0, printed = 0; i < input.length(); ++i)
{
if (isspace(input[i]))
continue;
std::cout << input[i];
printed++;
if (printed % 2 == 0)
std::cout << " ";
}
return 0;
}
Prints:
lo zp xc pz xz xp cp zx cp xz cl ol
try to modify i++ to i+=2, because you need to skip the second as first
The following takes two characters at a time and prints them. It uses the for syntax to initialize the chars and then to only proceed if reading two characters was successful.
for(char c1{}, c2{}; infile >> c1 >> c2;) {
std::cout << c1 << c2 << ' ';
}
try to use this instead i+=2, in order to avoid repetition.
if it reaches length() , then try using i<s.length().
i have taken s as the string here

Customer Decipher program c++ Trouble reading in

So I have a custom decipher program that reads in an input file and deciphers it based on the keys that are input.
Text file:
23
11
Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock. 1 I 0 random 2 computers, 0 not 0 the 0 open 2 car! 2 C, 0 lack 0 of 0 dog 1 green 2 C++ 0 bottle 2 wrong, 2 them. 0
5 1 10 21 9 6 21 11 13 16 20
This file is represented as:
[Number of Words]
[Number of Keys]
[Word] [Jump] [Word] [Jump] ... [Word] [Jump]
[Key] [Key] ... [Key]
I have managed for the program to read in the number of keys and amount of words, however I have having trouble reading in the words and the numbers next to them as well as the last numbers and registering those as keys. This is what I have so far:
#include <iostream>
#include <fstream>
using namespace std;
struct pieces {
char word;
int jump;
} ;
// Main Function
int main ()
{
// declare variables
int keyCount = 1;
int wordCount = 8;
int wordAmount[8];
int keyAmount[8];
pieces cipher[5];
char decoded[20][20];
char filename[10];
int keys[keyCount];
char tArray[20][20];
ifstream inData;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
inData.open(filename);
if(inData.is_open());
{
// read list of names into array
for ( int i = 0; i < keyCount; ++i){
inData >> wordAmount[i] >> keyAmount[i];
for(int j = 0; j < wordCount; j++){
inData >> cipher[j].word >> cipher[j].jump;
}
}
cout << " Key Count: " << keyCount << "\n";
// print out
for ( int i = 0; i < keyCount; ++i){
cout << " KeyAmount: ";
cout << keyAmount[i] << "\n";
cout << " WordAmount: ";
cout << wordAmount[i] << "\n";
for(int j = 0; j < wordCount; j++){
cout << cipher[j].word << " " << cipher[j].jump;
}
}
}
inData.close();
return 0;
}
I did try putting the char word as an array but then I got a segmentation file. Any advice would be appreciated!
IMHO, your project would be simpler if you used std::string and overloaded the formatted input operator >>:
struct Word_Jump
{
std::string word; // Using std::string because it has space for more than one character.
int jump;
friend std::istream& operator>>(std::istream& input, Word_Jump& wj);
};
std::istream&
operator>>(std::istream& input, Word_Jump& wj)
{
input >> wj.word;
input >> jump;
return input;
}
Your input could look something like this:
std::vector<Word_Jump> database;
for (unsigned int i = 0; i < number_of_words; ++i)
{
Word_Jump wj;
my_data_file >> wj;
database.push_back(wj);
}
Similarly, you input for reading keys:
std::vector<int> key_database;
for (unsigned int j = 0; j < number_of_keys; ++j)
{
int k = 0;
my_data_file >> k;
key_database.push_back(k);
}
So the above are two possible methods for reading in the word & jump pairs and also the keys.

How to make an integer vector ignore white space and add 2 to every element in C++ [duplicate]

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
I have a weird problem, so my instructor told us to create a simple program using vectors that will first ask the user how many integers they want to enter, and after the numbers were entered via a space as a delimiter the output should add 2 to each vector element.
Ex -
How many numbers are you going to enter = 4 (Lets assume the user enters 4)
Enter the numbers = 11 45 71 24 (Lets assume the user entered these 4 numbers)
THE OUTPUT SHOULD BE THIS = 13 47 73 26 (with spaces added 2)
Since using vectors is a must, i know how to add add 2 with a normal integer vector output but when it comes with spaces i have no idea, so far the program i wrote will accept everything before the space into the vector and will add 2 to it.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <int> userInput;
int input;
int number;
int num1;
cout << "How many numbers are you going to enter ? :";
cin >> number;
cout << "Enter the Numbers : " << endl;
cin >> input;
userInput.push_back(input);
cout << "Vector Contains : ";
for (unsigned int i = 0; i < userInput.size(); i++)
{
cout << userInput[i] + 2;
}
system("pause>nul");
return 0;
}
The reason you're only taking in one input is because you're only taking in one int from std::cin. The other ints are still remaining in the stream. You should do this:
while(/*we still have stuff to extract*/)
{
std::cin >> input;
userInput.push_back(input);
}
However, we still need to know when to stop. Since we're only expecting one line of input from the user, we can do std::cin.peek() != '\n' to check if we've reached the point where the user pressed the Enter key earlier.
Thank you for reading.
The standard extraction operator for int expects whitespace as the separator between items so you don't need to do anything special there. Just read ints, put them in your vector, do the addition, and print out the results. Assuming you've already read n for the count, the real work could look something like this:
std::copy_n (std::istream_iterator<int>(std::cin),
n,
std::back_inserter(your_vector));
std::transform(your_vector.begin(), your_vector.end(),
std::ostream_iterator<int>(std::cout, " "),
[](int i){ return i + 2; });
Try the following
#include <iostream>
#include <vector>
#include <cstdlib>
int main()
{
std::cout << "How many numbers are you going to enter ? :";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " numbers : " << std::endl;
int x;
for ( size_t i = 0; i < n && std::cin >> x; i++ ) v[i] = x;
for ( int x : v ) std::cout << x + 2 << ' ';
std::cout << std::endl;
std::system( "pause>nul" );
return 0;
}
If to input
4
11 45 71 24
the output will be
13 47 73 26
Other approach is to use standard function std::getline and std::istringstream instead of the operator >>
For example
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <sstream>
#include <limits>
int main()
{
std::cout << "How many numbers are you going to enter ? :";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " numbers : " << std::endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::string s;
std::getline( std::cin, s );
std::istringstream is( s );
int x;
for ( size_t i = 0; i < n && is >> x; i++ ) v[i] = x;
for ( int x : v ) std::cout << x + 2 << ' ';
std::cout << std::endl;
std::system( "pause>nul" );
return 0;
}

cin.getline () is not working when called the second time [duplicate]

This question already has answers here:
Why getline skips first line?
(3 answers)
Closed 9 years ago.
In this code ,getline is not working for i =1 .but for i = 0 it is working completely fine.
What I should do to repeatedly work with the getline function.This code takes a number and checks its divisibility."numb" is taken to store the number.for i = 0 all the calcultions are just fine but when it goes for the 2nd turn ,don't know what happens but cin.getline doesn't work.
#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#define MAX 1050
using namespace std ;
int call_div (char *num ,long div)
{
int len =strlen (num) ;
int now ;
long extra ;
for (now = 0,extra=0; now < len; now += 1)
{
extra = extra *10 + (num [now] -'0') ;
extra = extra %div ;
}
return extra ;
}
int main (int argc, char const* argv[])
{
int testcase,numbers ,flag =0;
char numb[MAX] ;
cin >> testcase ;
getchar() ;
for (int i = 0; i < testcase; i += 1)
{
cout << i << endl ;
int div[14] ;
cin.getline(numb) ; // i= 0 ,it works fine ,i=1 ,it doesn't work
cin >> numbers ;
for (int j = 0; j < numbers; j += 1)
{
cin >> div[j] ;
}
for (int k = 0; k < numbers; k += 1)
{
// cout << div[k]<< ' ' << call_div (numb,div[k]) << endl ;
if (call_div (numb,div[k])==0)
{
flag = 1 ;
}
else {
flag = 0 ;
break;
}
}
if (flag==0 )
{
cout << "simple"<< endl ;
}
else
cout << "wonderful" << endl ;
}
return 0;
}
I think Your input may look like
something
3 1 2 3
some other thing
4 1 2 3 4
First time You read "something" with getline(). Then your algorithm reads the 3 as numbers, and then the three number followed by that one. And here reading stops. Next time You call getline(), it will continue reading until it reaches the first '\n' character. So it will not read "some other thing" when You want it.
Now I can not try it, but I think it will work fine with an extra "dumb" getline() after the loop that fills the div array.