c++ - How do I compare two different strings from two separate text files? -
i c++ rookie , not know doing wrong. assignment compare 2 different .txt files, each containing item along either number of items , price of item. trying print names , prices of items. lets using .txt file namesandquantity.txt includes:
3 books 4 pens
and .txt file namesandprice.txt includes:
pens 3.45 books 19.55
the code using prints out first match:
#include <iostream> #include <fstream> #include <cmath> int main(){ string nameofitemp, nameofitemq; double priceofitem; int numberofitems; ifstream indata; ifstream indata2; indata.open("namesandquantity.txt"); indata2.open("namesandprice.txt"); while (indata>>numberofitems>>nameofitemq){ while (indata2>>nameofitemp>>priceofitem){ if (nameofitemp==nameofitemq){ cout<<nameofitemq<<endl; cout<<priceofitem; } } }
this code prints out first line:
books 19.55
what can better it?
it's because after first
while (indata2>>nameofitemp>>priceofitem){ if (nameofitemp==nameofitemq){ cout<<nameofitemq<<endl; cout<<priceofitem; }
executes, indata2
reaches end , not read more. solution move open
function while
loop:
while (indata>>numberofitems>>nameofitemq){ indata2.open("namesandprice.txt"); while (indata2>>nameofitemp>>priceofitem){ if (nameofitemp==nameofitemq){ cout<<nameofitemq<<endl; cout<<priceofitem; } indata2.close(); }
however, not best approach. you'd better use map
avoid nested loops. map
array except can choose use string
index:
#include <iostream> #include <fstream> #include <string> #include <map> using namespace std; int main() { // same before int numberofitems; string nameofitem; double price; // create map, using string index , int value. map<string, int> items; ifstream indata("namesandquantity.txt"); ifstream indata2("namesandprice.txt"); while (indata >> numberofitems >> nameofitem) items[nameofitem] = numberofitems; while (indata2 >> nameofitem >> price) cout << nameofitem << " " << items[nameofitem] << " " << price << endl; indata.close(); indata2.close(); return 0; }
output
pens 4 3.45 books 3 19.55
Comments
Post a Comment