I have this school project of mine and I need some help to troubleshoot; I've debugged as far as if it goes into the while(prod_file.good()) loop and it does, it just fails to find an existing string within a file.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define PROD_SIZE 22
class PRODUCT {
public:
string NAME;
string QUANTITY;
} product;
int main() {
int diff;
string length;
char answer = 0;
string line;
bool foundAndReplaced = false;
cout << product.NAME.length() << endl;
cout << product.NAME;
fstream prod_file("data/available.dat", ios::out | ios::app);
do {
if(prod_file.is_open()) {
cout << "Molq vavedete imeto na produkta: \n";
getline(cin, product.NAME);
if(product.NAME.length() < 30) {
diff = 30 - product.NAME.length();
for(int i = 1; i < diff; i++){
product.NAME.append(".");
}
}
else if(product.NAME.length() > 30) {
cout << "Product name cannot exceed 30 characters.";
return 0;
}
//
cout << "Molq vavedete kolichestvoto na produkta: \n";
getline(cin, product.QUANTITY);
size_t pos;
while(prod_file.good()) {
cout << "asd\n";
getline(prod_file, line);
pos = line.find(product.NAME);
cout << "stignah\n";
if(pos != string::npos) {
prod_file << product.NAME;
prod_file << "-" << product.QUANTITY << "\n";
}
}
}
else {
cout << "Error: File inaccessible. (0x1)";
return 0;
}
cout << "Do you want to add more products? Y/N \n\n";
answer = 0;
while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N') {
answer = _getch();
}
}
while(answer == 'Y' || answer == 'y');
prod_file.close();
cout << "Entries added." << "\n\n";
return 0;
}
The idea of
size_t pos;
while(prod_file.good()) {
cout << "asd\n";
getline(prod_file, line);
pos = line.find(product.NAME);
cout << "stignah\n";
if(pos != string::npos) {
prod_file << product.NAME;
prod_file << "-" << product.QUANTITY << "\n";
}
}
Is to check for a certain string in a file and if it does not find the string to add to the file, if it finds it then it will not add it. Any idea why it fails the if?