Я новичок в программировании, поэтому я мог бы использовать вашу помощь с моим кодом. Я пытаюсь прочитать существующий файл с данными, отформатированными следующим образом:
2012-09-22|microsoft|0|102.36|100
2012-09-22|apple|0|203.12|100
2012-10-05|ibm|0|141.96|100
2012-10-05|boeing|0|123.65|100
2012-11-03|sears|0|23.36|100
2012-11-29|toyota|0|78.45|100
Я отправляю весь свой код, но соответствующей функцией является void loadData (транзакция allTransaction); функция. Я взломал этот код из нескольких примеров, которые я нашел здесь, но он не работает для меня. Я пытаюсь читать данные, а затем заполнять переменные структуры allTransaction. Затем я хочу подтолкнуть эту структуру к вектору данных. Я хочу, чтобы цикл каждой линии, пока я не дойду до конца файла. Похоже, что я не получаю значения заложенной структуры. Пожалуйста помоги!
Я занимаюсь этим программированием уже 2 месяца для школы, поэтому, пожалуйста, держите свои ответы на уровне noob.
благодаря
#define _CRT_SECURE_NO_DEPRECATE // Declaration to use deprecated code in Visual Studio.
#include <iostream> // Include the iostream standard file.
#include <string> // Include the string library.
#include <fstream> // Include to manipulate files.
#include <vector> // Include to use vectors.
#include <sstream> // Include to use stringstream.
#include <ctime> // Include to calculate time.
using namespace std;
// Create transactions structure
struct transaction
{
/*int user = 0;*/
string date = "";
string stock = "";
bool sale = 0;
double price = 0.0;
int shares = 0;
};
// Create vector
vector <transaction> data;
// Function declarations
void loadData(transaction allTransaction);
void buyShares(transaction allTransaction);
void sellShares(transaction allTransaction);
void storeData(transaction allTransaction);
int main()
{
// Declare variables
transaction allTransaction; // Declaring a structure.
loadData(allTransaction);
cout << "Date: " << allTransaction.date <<
"Name: " << allTransaction.stock <<
"Sale?: " << allTransaction.sale <<
"Price: " << allTransaction.price <<
"Shares: " << allTransaction.shares;
//Pause program
cout << "Press Enter To Continue..." << endl;
cin.ignore();
cin.get();
return 0;
}
// Load text file function
void loadData(transaction allTransaction)
{
string line;
ifstream myfile("data.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
istringstream f(line);
string s;
while (getline(f, s, '|')) {
myfile >> allTransaction.date >>
allTransaction.stock >>
allTransaction.sale >>
allTransaction.price >>
allTransaction.shares;
data.push_back(allTransaction);
}
myfile.close();
}
}
else std::cout << "Unable to open file";
}
// Buy stock function
void buyShares(transaction allTransaction)
{
allTransaction.sale = 0; // Set sale boolean to 0, indicating a buy.
storeData(allTransaction); // Call storeData function to store the data.
}
// Sell stock function
void sellShares(transaction allTransaction)
{
allTransaction.sale = 1; // Set sale boolean to 1, indicating a sell.
// Need function to check shares on hand.
storeData(allTransaction); // Call storeData function to store the data.
}
void storeData(transaction allTransaction)
{
ofstream myfile;
myfile.open("data.txt", ios::out | ios::app);
myfile << allTransaction.date << "|" << allTransaction.stock << "|" << allTransaction.sale << "|" <<
allTransaction.price << "|" << allTransaction.shares << '\n';
myfile.close();
data.push_back(allTransaction);
}
Одна вещь, которая появляется в моих глазах, - это цикл:
while (getline(f, s, '|')) {
myfile >> allTransaction.date >>
allTransaction.stock >>
allTransaction.sale >>
allTransaction.price >>
allTransaction.shares;
data.push_back(allTransaction);
}
Сначала вы читаете из потока f с разделителем '|' (что хорошо), но внутри тела цикла while вы снова читаете из файла (что не то, что вы хотите). Вы можете сделать что-то подобное.
std::vector<std::string> v;
while (getline(f, s, '|')) {
v.push_back(s);
}
if(v.size()!=5) {
std::cerr << "expected 5 values" << std::endl;
return false; // or throw an exception etc...
}
// At this point you have a vector with the strings
// delimited by '|' ready for processing
// into your allTransaction class