I would really need your help on this one and I hope I'll get some clue about my compiler error.
The problematic piece of my code:
char user_ch;
do {
user_ch=_getch(); // i changed it from getch() to fix the previous error, didn't help it seems
switch (user_ch) {
case '1': response='1'; break;
case '3': response='3';
}
} while (response!='1'||response!='3');
Compiler error (what's peculiar it's 'build' error instead of 'debug' error):
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
Compiler refers to this piece of code in fstream file:
private:
_Myfb _Filebuffer; // the file buffer
};
As someone pointed out I'm posting my usage of fstream functions and objects.
My functions parsing settings.txt file
bool read_bool(ifstream file, int verse) {
string temp_var;
for (int i=0; i<verse; i++)
getline(file, temp_var);
if (temp_var=="true") return true;
else return false; }
int read_int(ifstream file, int verse) {
string temp_var;
for (int i=0; i<verse; i++)
getline(file, temp_var);
return stoi(temp_var); }
t_direction read_t_dir(ifstream file, int verse) {
char temp_var;
for (int i=0; i<verse; i++)
file.get(temp_var);
t_direction pre_return;
switch (temp_var) {
case '1': pre_return=to_mother; break;
case '2': pre_return=to_foreign; break;
case '3': pre_return=rndom;
}
return pre_return; }
string read_string(ifstream file, int verse) {
string temp_var;
for (int i=0; i<verse; i++)
getline(file, temp_var);
return temp_var; }
size_t lines_count(ifstream if_file) {
size_t a=0;
string temp_str;
while (getline(if_file, temp_str))
++a;
return a; }
bool add_mistake(ofstream file, string mistake, string to_trans, string target) {
file << "Original: " << to_trans << "\nShould be: " << target;
file << "\nYour response: " << mistake;
file << "\n---------------------\n";
return true; }
For error-security sake i've never opened or closed fstream object inside a function.
// stream from file and tokenize
// SYNTAX FOR FILE (each line): word,word>word,word,word
words_input.open(FILE_NAME);
string buffer_line, token;
for (size_t i; i<number_of_lines; i++) {
getline(words_input, buffer_line);
istringstream language_split(buffer_line);
vector<string> container(2);
while (getline(language_split, token, '>')) // split languages
container.push_back(token); // hard coded to ignore possible elements 3, 4, 5...
istringstream synonym_source_split(container.at(0));
while (getline(synonym_source_split, token, ',')) // first language synonyms
source_words[i].push_back(token);
istringstream synonym_target_split(container.at(1));
while (getline(synonym_target_split, token, ',')) // second language synonyms
target_words[i].push_back(token);
}
words_input.close();
Thanks for any help!
Your issue is in this part of the code:
string read_string(ifstream file, int verse) {
string temp_var;
for (int i=0; i<verse; i++)
getline(file, temp_var);
return temp_var;
}
size_t lines_count(ifstream if_file) {
size_t a=0;
string temp_str;
while (getline(if_file, temp_str))
++a;
return a;
}
Both of these functions take as input a parameter of type ifstream. Since you're not taking in the ifstream by reference, when you call this function, C++ will try to initialize if_file to a copy of the ifstream that you passed in as a parameter. This isn't allowed, since ifstreams can't be copied. Unfortunately, you tend to get garbage error messages like the one you showed above instead of something more useful in this case.
To fix this, change your code so that you take the parameters by reference:
string read_string(ifstream& file, int verse) {
string temp_var;
for (int i=0; i<verse; i++)
getline(file, temp_var);
return temp_var;
}
size_t lines_count(ifstream& if_file) {
size_t a=0;
string temp_str;
while (getline(if_file, temp_str))
++a;
return a;
}
That said, there are likely other errors in your code. I would strongly recommend commenting your code as you go and testing pieces incrementally, since as written the code is pretty tough to follow.
Related
I need to be able to read in (first number is meant to be id number followed by transactions, making bank statement code, d means deposit, w is withdrawal, numbers after are amount):
123 d45.10 d50.45 d198.56 w45.67
345 w34.00 d4.56 w45.13 d23.23 w23.12
639 d1000.34 d1234.56 w34.33 w345.87 w22.13
890 d345.67 d123.67 d45.99 d45.99 w34.77
666 d66.60 d666.66 d6.66 d66.6 d6666.66
and have it sort into different arrays all stored within a struct. I have tried string stream and various other things i thought of, I'm like medium versed in c++, in the first year class to be specific.
This is the code I have so far, The first set of read ins is working properly but I cannot get the second one to work:
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
struct PersonAcct {
int acct_num[5];
string name[5];
double acct_bal[5];
};
struct PersonTrans {
int acct_num[5];
double trans[20];
char d_p[20];
};
int main() {
ifstream ifacc("accounts.txt");
PersonAcct p;
if (ifacc.is_open()) {
for (int i = 0; i <= 4; i++) {
ifacc >> p.acct_num[i];
ifacc >> p.name[i];
ifacc >> p.acct_bal[i];
}
}
ifacc.close();
ifstream iftrans;
iftrans.open("transactions.txt");
PersonTrans q;
string line,line2,line3,line4,line5;
if (iftrans.is_open()) {
int counter = 0;
while (getline(iftrans,line)) {
cout << line << endl;
counter++;
}
}
return 0;
}
Any help would be much appreciated! As I said before I am pretty new in retrospect to most of you on here so please be detailed or explain it for someone a bit daft in this subject, as I prob could be considered. I thank you and wish you a happy early holiday season!
If I understand you correct, you need to parse different words in different lines. You should be able to get this done easily with std::stringstream.
e.g.
...
iftrans.open("transactions.txt");
if (iftrans.is_open())
{
int counter = 0;
string line;
while (getline(iftrans, line)) // iterate through lines
{
int id;
string word;
stringstream ss(line);
ss >> id; // first word is the ID
while (ss >> word) // iterate though words of current line
{
switch (word[0]) // a word starts with either `w` or `d`
{
case 'w':
{
// remaining characters represent a valid double
double const val = stod(word.substr(1));
// process withdrawal
// ...
break;
}
case 'd':
{
double const val = stod(word.substr(1));
// process deposit
// ...
break;
}
default: break; // error?
}
}
counter++;
}
}
You may need to do additional error handling if the commented assumptions are not guaranteed to be valid always.
So I probably implemented it stupidly but here's what I thought you should do. Since the first thing will always be an ID I added that to acct_num;
Next I have a while loop for the line, I create a new string stream (Probably bad form, unsure) using a substring of everything after the first letter. Then I check the first letter of each transaction whether or not its a d or a w and put them into arrays. I had two counters for the w and d arrays. If they were vectors this wouldn't be necessary.
I wasn't sure what your original struct meant so I just created an array for deposits and withdrawals.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
struct PersonTrans {
int acct_num[5];
double deposits[20];
double withdrawals[20];
};
int main() {
ifstream iftrans;
iftrans.open("transactions.txt");
PersonTrans q;
if (iftrans.is_open()) {
int i = 0;
int d = 0;
int w = 0;
string line;
while (getline(iftrans,line)) {
stringstream in(line);
string tmp;
int idNumber;
in >> idNumber;
q.acct_num[i] = idNumber;
while(in >> tmp) {
double value;
std::stringstream transaction(tmp.substr(1));
transaction >> value;
if (tmp[0] == 'd'){
q.deposits[d] = value;
d++;
}
else if (tmp[0] == 'w'){
q.withdrawals[w] = value;
w++;
}
}
i++;
}
}
for(int i = 0; i < 20; i++){
cout << q.deposits[i] << endl;
}
return 0;
}
This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 5 years ago.
I am a college student and as part of my final project for a c++ class we are assigned to read a csv file that has distance and force data and then find torque from it. The problem that I am running into is how to actually get the data out of the csv file into a workable format. Currently I have been trying to get it into a matrix, to do this though I will need to first determine the size of the csv file as it is supposed to take any size file. This is the format of the data
Case 1,,,,,x_position (m),y_position (m),z_position (m),F_x (N),F_y (N),F_z (N)16.00,5.00,8.00,394.00,-18.00,396.0022.00,26.00,14.00,-324.00,-420.00,429.0028.00,25.00,21.00,73.00,-396.00,-401.006.00,9.00,12.00,-367.00,-137.00,-143.00
Also obviously the different data pieces (distance and forces) need to be put into different vectors or matrices.
This is what I have so far to try to find the number of lines in the file.
ifstream myfile("force_measurements.csv");
if(myfile.is_open()){
string line;
double num=0;
getline(myfile, line);
if(line==""){
cout<<num<<endl;
myfile.close();
}
else{
num++;
}
}
After this works how would you go about putting the data into a matrix? or would a different format be easier? vectors was my other though.
// you need to include the proper headers here
class vec3D:
{
double m_x, m_y, m_z;
public:
void Set(size_t indx, double val)
{
switch(indx)
{
case 0:
m_x = val;
break;
case 1:
m_y = val;
break;
case 2:
m_z = val;
break;
default:
std::cout << "index out of range" << std::endl;
}
}
double magnitude() { return std::sqrt( m_x*m_x + m_y*m_y + m_z*m_y);}
};
int main()
{
std::ifstream my_data_file ( "your_file_here.csv" );
std::vector<std::array<vec3D, 2>> Pos_Forz;
if ( ! my_data_file.is_open())
{
std::cout << "failure to open the file" <<std::endl;
return -1;
}
std::string temp_str;
double arr[6];
std::array<vec3D,2> temp_3Dvec;
while(!my_data_file.eof())
{
for (int i = 0; i<5 ; i++)
{
getline(my_data_file, temp_str, ",");
arr[i] = std::stod(temp_str);
}
getline(my_data_file, temp_str);
arr[5] = std::stod(temp_str);
for(int i = 0; i<2; i++)
{
for (int j=0; j<3; j++)
{
temp_3Dvec[i].set(j, arr[i*3 + j]);
}
}
Pos_Forz.push_back(temp_3Dvec);
}
for(auto e: Pos_Forz)
{
std::cout << " toque = " << (e[0].magnitude() * e[1].magnitude()) <<std::endl;
}
return 0;
}
Fix what need to be fixed, and inspire yourself from this code, also stop asking this kinda of questions here, you need to read the HOW TO of posting
You have multiple questions. Here's something I used for loading items out of a csv. This gets you started, and you can figure out whether further organization of the data is useful. I personally have classes that take a tokenized line and create an instance of themselves with them.
#include <boost/tokenizer.hpp>
typedef vector<string> csvLine;
void aFunction()
{
string line;
vector<csvLine> usedCollection;
ifstream csvFile("myfile.csv", ios::in);
if (!csvFile)
return -1;
while (getline(csvFile, line))
{
vector<string> tokenizedLine;
boost::tokenizer<boost::escaped_list_separator<char> > tk(
line, boost::escaped_list_separator<char>('\\', ',', '\"'));
for (const string& str : tk)
{
tokenizedLine.push_back(str);
}
usedCollection.push_back(tokenizedLine);
}
csvFile.close();
}
And so usedCollection is a collection of csvLines, where each of those is a collection of strings broken up by the separator character.
So the idea behind this is that a user inputs a message, and the message gets translated to Morse code. It is a homework assignment I've been working on for over 8 hours today. It's also my first time seriously working with classes.
When run, I get only one error on line 64. The error I got makes no sense (and it's huuuuge so I don't want to include it unless asked). I suspect the issue is that the originalMessage vector and alphaCode vector are different vector types (string & char respectively).
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Code
{
private:
vector<char> alphaCode;
vector<string> morseCode;
vector<string> originalMessage;
vector<string> finalMessage;
public:
Code();
void encoder(vector<string> input);
void display();
};
Code::Code():alphaCode(), morseCode(28)
{
//Building alphaCode
for (char c='A'; c<='Z'; c++) alphaCode.push_back(c);
alphaCode.push_back(' ');
alphaCode.push_back('.');
//Building morseCode
morseCode[0] =".-";
morseCode[1] ="-...";
morseCode[2] ="-.-.";
morseCode[3] ="-..";
morseCode[4] =".";
morseCode[5] ="..-.";
morseCode[6] ="--.";
morseCode[7] ="....";
morseCode[8] ="..";
morseCode[9] =".---";
morseCode[10] ="-.-";
morseCode[11] =".-..";
morseCode[12] ="--";
morseCode[13] ="-.";
morseCode[14] ="---";
morseCode[15] =".--.";
morseCode[16] ="--.--";
morseCode[17] =".-.";
morseCode[18] ="...";
morseCode[19] ="-";
morseCode[20] ="..-";
morseCode[21] ="...-";
morseCode[22] =".--";
morseCode[23] ="-..-";
morseCode[24] ="-.--";
morseCode[25] ="--..";
morseCode[26] =".......";
morseCode[27] ="x";
}
void Code::encoder(vector<string> input)
{
originalMessage = input;
for (int i = 0; i < originalMessage.size(); i++)
{
for (int j = 0; j < alphaCode.size(); j++)
{
if (originalMessage[i] == alphaCode[j])
{
finalMessage.push_back(morseCode[j]);
finalMessage.push_back(" ");
}
}
}
}
void Code::display()
{
for (int x; x < finalMessage.size(); x++) cout << finalMessage[x];
}
//------------------------------------------------------------------------------
int main()
{
vector<string> message;
string temp;
cout << "Input:" << endl;
cin >> temp;
message.push_back(temp);
Code c1;
c1.encoder(message);
c1.display();
}
You have a couple of problem in your source code.
The first problem is message variable:
vector<string> message;
Could be changed to:
string message;
And change other parts of your code, based on this change.
The second problem backs to
for (int x; x < finalMessage.size(); x++) cout << finalMessage[x];
variable x is not initited, initite it or write a better loop like this:
for (const auto& x : finalMessage) cout << x;
Please read the error message :
prog.cpp:64:36: error: no match for 'operator==' (operand types are 'std::basic_string' and 'char')
if (originalMessage[i] == alphaCode[j])
if (originalMessage[i] == alphaCode[j])
originalMessage is a vector<string> while alphaCode is vector<char>
There is no way you can compare char with a string
You may want to change your function this way:
void Code::encoder(vector<string> input)
{
originalMessage = input;
for (int i = 0; i < originalMessage.size(); i++)
{
string i_string = originalMessage[i]; // get the string here
for (int j = 0; j < alphaCode.size(); j++)
{
if (i_string.at(i) == alphaCode[j]) // get the char in string
{
finalMessage.push_back(morseCode[j]);
finalMessage.push_back(" ");
}
}
}
}
EDIT
Basically, we want to extract char information from the string
for (int i = 0; i < originalMessage.size(); i++) {
string i_string = originalMessage[i];
for (int j =0; i < i_string.size(); j++) {
char at_j = i_string.at(j);
// find this at_j in alphaCode
// enncode
}
}
I have been trying to read data from a binary file in C++, but I'm getting run time error, Program has stopped working!
I have used the similar code before and it is still working. I am getting an error while executing the constructor of the class SettingsClass [Maybe because of the read function, because after removing it, everything just ran great.]
struct Setting{
int SettingID;
int SettingINTValue;
double SettingDOUBLEValue;
char SettingCHARValue;
string SettingSTRINGValue;
string SettingName;
};
class SettingsClass {
public:
void ResetSettings() {
fstream SettingFile;
Setting defaultsetting[NoOfSettings];
for(int i=1;i<=NoOfSettings;i++) {
defaultsetting[i-1].SettingID = i;
defaultsetting[i-1].SettingINTValue = 0;
defaultsetting[i-1].SettingDOUBLEValue = 0.0;
defaultsetting[i-1].SettingCHARValue = '#';
defaultsetting[i-1].SettingSTRINGValue = "null";
switch(i) {
default:
defaultsetting[i-1].SettingName = "Compression Levels";
defaultsetting[i-1].SettingSTRINGValue = "Normal";
defaultsetting[i-1].SettingINTValue = 1;
break;
}
cout<<i<<". "<<defaultsetting[i-1].SettingName<<"\n\t "<<defaultsetting[i-1].SettingINTValue<<"\n\t "<<defaultsetting[i-1].SettingDOUBLEValue<<"\n\t "<<defaultsetting[i-1].SettingCHARValue<<"\n\t "<<defaultsetting[i-1].SettingSTRINGValue<<"\n\t ";
cout<<"\n";
}
SettingFile.open(SettingsFilePath,ios::binary|ios::out);
if(SettingFile.is_open()){
SettingFile.write(reinterpret_cast<char const *>(&defaultsetting),sizeof(defaultsetting));
} else {
cout<<"Error!";
}
SettingFile.close();
}
SettingsClass() {
fstream SettingFile;
SettingFile.open(SettingsFilePath,ios::binary|ios::in);
if(SettingFile.is_open()) {
Setting TempSettings[NoOfSettings];
SettingFile.read((char*)&TempSettings,sizeof(TempSettings));
} else {
cout<<"Error...";
}
SettingFile.close();
}
} Settings;
You should go read and learn more about file streams and the associated input and output operators << and >>. You cannot simply input characters into an array like this line of code:
SettingFile.read((char*)&TempSettings,sizeof(TempSettings));
The array is not of char and yet you cast it as such. Instead you should loop over the available input and fill in the array, e.g.:
for(size_t i = 0; i<NoSetting; ++i) {
SettingFile >> TempSettings[i];
}
Of course you should overload the appropriate input operator:
istream& operator>>(istream& _is, Setting& _s) {
//read all variables of setting, i.e.:
//_is >> _s.var1;
//_is >> _s.var2;
//etc.
}
You likely have the same error for your output. You should overload:
ostream& operator<<(ostream& _os, const Setting& _s) {
//output all variables of Setting, e.g.:
//_os << _s.var1;
}
Do something like this instead of filestream write:
for(size_t i = 0; i<NoSetting; ++i) {
SettingsFile << defaultSetting[i];
}
I am working on a translation/transliteration program, that reads an english story, and translates it to elvish, using an english/elvish dictionary. After the code shown below, i explain the error that i receive.
I have a lot of code, I am not sure if i should post it all, but I will post what I think should be sufficient. Apologies if my code seems bizarre - but I am only a beginner.
There is a main file, a header file with two Classes: Translator and Dictionary, and a cpp file to implement the class functions.
I have a constructor that reads in the dictionary file to dictFileName and copys the english words into englishWord, and the elvish words into elvishWord:
Translator::Translator(const char dictFileName[]) : dict(dictFileName)
{
char englishWord[2000][50];
char temp_eng_word[50];
char temp_elv_word[50];
char elvishWord[2000][50];
int num_entries;
fstream str;
str.open(dictFileName, ios::in);
int i;
while (!str.fail())
{
for (i=0; i< 2000; i++)
{
str>> temp_eng_word;
str>> temp_elv_word;
strcpy(englishWord[i],temp_eng_word);
strcpy(elvishWord[i],temp_elv_word);
}
num_entries = i;
}
str.close();
}
In the main file, the english lines are read into the toElvish function, and tokenized into an array of words, temp_eng_words.
Within this toElvish function, I am calling another function; translate, which reads in temp_eng_words and is supposed to return the elvish words:
char Translator::toElvish(char elvish_line[],const char english_line[])
{
int j=0;
char temp_eng_words[2000][50];
//char temp_elv_words[2000][50]; NOT SURE IF I NEED THIS
std::string str = english_line;
std::istringstream stm(str);
string word;
while( stm >> word) // read white-space delimited tokens one by one
{
int k=0;
strcpy (temp_eng_words[k],word.c_str());
k++;
}
for (int i=0; i<2000;i++) // ERROR: out_s was not declared in this scope
{
Dictionary::translate (out_s,temp_eng_words[i]); // ERROR RELATES TO THIS LINE
}
}
This is the translate function:
char Dictionary::translate (char out_s[], const char s[])
{
int i;
for (i=0;i < numEntries; i++)
{
if (strcmp(englishWord[i], s)==0)
break;
}
if (i<numEntries)
strcpy(out_s,elvishWord[i]);
}
My problem is that when I run the program, I get the error '*out_s was not declared in this scope*'.
If you have read all of this, thanks; any suggestions/clues would be much appreciated. :)
As you can see in your code below, you have used out_s in your function, but you have not declared it in your function.
You can use global variables or local variables in your function. I suggest you read this
char Translator::toElvish(char elvish_line[],const char english_line[]) {
int j=0;
char temp_eng_words[2000][50];
//char temp_elv_words[2000][50]; NOT SURE IF I NEED THIS
std::string str = english_line;
std::istringstream stm(str);
string word;
while( stm >> word) // read white-space delimited tokens one by one
{
int k=0;
strcpy (temp_eng_words[k],word.c_str());
k++;
}
for (int i=0; i<2000;i++) // ERROR: out_s was not declared in this scope
{
Dictionary::translate (out_s,temp_eng_words[i]); // ERROR RELATES TO THIS LINE
}}