Hello, I am trying to write a code in which the user enters a normal number like 1 or 4 and the program searches a text file for the corresponding the number. The file looks like this:
number#value
1#23400
4#17000
5#21000
6#12600
9#26700
How do I get the program to read a line only up until the # and recognize that that is the corresponding number and then cout the value?
ifstream inputFile;
inputFile.open("filename.txt");
string getData;
getline(inputFile, getData); // This gets the entire line and stores it as string in string getData
string num = getData.substr(2,5); // This extrats chars from index 2 (first digit) until 5 spaces (which is last digit of you number)
You can put that into a loop and do this for each line (i.e each number).
If you want to convert the extracted number from string type to int, you can do so by using stoi
function. http://www.cplusplus.com/reference/string/stoi/
cout << "Hello this program will display a salary with its corresponding code number." << endl;
cout << "Please enter your code number with '#' at the end of it. ";
cin >> code;
Here's something I wrote for you quickly, but I hope this gives you a better understanding on how you could do something like this in the future. Please ask any questions if needed.
#include <iostream>
#include <fstream> // for ifstream
#include <string> // for getline
int main()
{
constchar INDEX_SYMBOL = '#';
std::ifstream file("Payroll.txt", std::ifstream::in);
std::string tempString = "";
char index = '0';
bool indexFound = false;
if (file.is_open() == true)
{
std::cout << "Hello this program will display a salary with its corresponding code number.\n";
std::cout << "Please enter your code number: ";
index = getchar();
while (file.eof() == false && indexFound == false)
{
// Read file line
std::getline(file, tempString);
// Create unique index string
std::string uniqueIndex = "";
uniqueIndex += index;
uniqueIndex += INDEX_SYMBOL;
// Check if the line contained the unique index
// If the index was found display the data
// and end the program
if (tempString.find(uniqueIndex) != std::string::npos && file.good() == true)
{
std::cout << "\nSalary:\n";
std::cout << tempString.substr(2, tempString.size() - 2) << std::endl;
indexFound = true;
break;
}
}
file.close();
}
else
{
std::cout << "Error: Couldn't open file\n";
return 0;
}
if (indexFound == false)
std::cout << "\nThe index did not exist in the file!\n";
return 0;
}