从C ++文本文件中提取和使用特定数据 [英] Extract and use specific data from a text file in C++
问题描述
好吧,我设法从文件中提取了我想要的数据,但是在尝试计算提取的数字(执行加法)时出现了问题.
Ok, I managed to extract the data I wanted from a file, but there is a problem when trying to calculate those extracted numbers (perform addition).
数字存储在这里 cout<< stod(line.substr(position + 1))<< endl;
The numbers are stored here cout << stod( line.substr( position + 1 ) ) << endl;
我尝试过这样
sum = stod( line.substr( position + 1 ) );
sum = sum * 5.0;
cout << sum << endl;
由于这是一个while循环,所以我的程序又再次执行计算,所以我将每个价格乘以5,但是我只想做加法运算:sum + sum + sum + sum + sum + sum. 我什至写了那封信,我当然也得到了同样的东西.
Since this is in a while loop, my program performes the calculation again adn again, so I get each price multiplied by five, but I only want to do addition like: sum+sum+sum+sum+sum. I even wrote that and I of course get the same thing.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
void KeyWord(ifstream &FileSearch)
{
string line;
string letters[5];
long sum[6];
ifstream readSearch;
cout<< "Enter a barcode of a product: \n";
cin >> letters[0];
cin >> letters[1];
cin >> letters[2];
cin >> letters[3];
cin >> letters[4];
readSearch.open("Products.txt");
if(readSearch.is_open())
{
while (getline(readSearch, line))
{
while (line.find(letters[0])!=string::npos || line.find(letters[1])!=string::npos || line.find(letters[2])!=string::npos || line.find(letters[3])!=string::npos || line.find(letters[4])!=string::npos)
{
cout << line << "\n";
auto position = line.find( "$" );
if( position <= line.size() )
{
cout << stod( line.substr( position + 1 ) ) << endl;
break;
}
}
}
}
}
int main()
{
ifstream file("Products.txt");
KeyWord(file);
return 0;
}
推荐答案
这里有些蛮力供您使用.
Here's some brute force for you to play with.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
double getPrice( string inputLine )
{
auto position = inputLine.find( "$" );
if( position <= inputLine.size() )
{
return stod( inputLine.substr( position + 1 ) );
}
return 0;
}
string getBarCode( string inputLine )
{
auto position = inputLine.find( '$' );
position -= 1;
string barCode;
while( isspace( inputLine[ position ] ) )
{
--position;
}
while( ! isspace( inputLine[ position ] ) )
{
barCode.insert( barCode.begin(), inputLine[ position-- ] );
}
return barCode;
}
int main( int argc, char** argv )
{
cout << "Enter barcode: " << endl;
string barcodeInput;
getline( cin, barcodeInput );
ifstream inputFile( "Products.txt" );
if( inputFile.is_open() )
{
string inputLine;
while( getline( inputFile, inputLine) )
{
auto price = getPrice( inputLine );
if( price != 0 )
{
if( getBarCode( inputLine ) == barcodeInput )
{
cout << "Price: " << price << endl;
inputFile.close();
return 0;
}
}
}
cout << "No matching barcode." << endl;
inputFile.close();
}
return 0;
}
这篇关于从C ++文本文件中提取和使用特定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!