error C2664 char [80] to char [duplicate] - c++
This question already has an answer here:
invalid conversion from 'int' to 'char *'
(1 answer)
Closed 8 years ago.
Hi I am suppose to create a program to read a .txt file and save the information in the txt to a struct and enum (have to use enum. as it compulsory) then prints out the information after rearranging the words. eg
Sarah
Wonderland
Libra 2 - 10 - 1993
3
I want to...
I hope to...
............
TO
My name is sarah
my nationality is wonderland
my bday is 2 october 1993
I am a libra
I have 3 wishes
1. I want to...
2. I hope to...
3. ............
I have encountered similar error C2664 for getHoroNum and checkHoro stating that it cant convert parameter 1 from 'char [80]' to 'char'. Please help! Thanks a lot in advance!
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 80;
const int MAXNO = 10;
enum Zodiac
{
Aquarius, Pisces, Aries, Taurus,
Gemini, Cancer, Leo, Virgo,
Libra, Scorpio, Sagittarius, Capricorn
};
struct Date
{
Zodiac sign;
int day;
int month;
int year;
};
struct Student
{
char name [MAX];
char nationality [MAX];
Date birthDate;
int no; // no of other messages
char wishMessage [MAXNO][MAX];
};
void myInfo (fstream&, char [], Student&);
// The above function reads information from the text file
// and store the information in a structure reference parameter
void printOut(Student , char[], char[]);
void getHoroNum(char , Student&);
void checkHoro (char , Student);
void getMth (int, char []) ;
int main()
{
fstream infile;
char fName[MAX];
char horo [MAX];
char fHoro[MAX];
char mth[MAX];
int month;
Student info;
cout << "Enter your info file name: ";
cin >> fName;
cout << endl;
month = info.birthDate.month;
myInfo(infile, fName, info);
getHoroNum(horo, info);
checkHoro(fHoro, info);
getMth(month, mth);
printOut(info, );
}
void myInfo (fstream& infile, char fName[], Student& info)
{
infile.open(fName, ios::in);
char temp[MAX];
char horo[MAX];
if(!infile)
{
cout << "Error file not found!" << endl;
exit(0);
}
infile.getline(info.name, MAX);
infile.getline(info.nationality,MAX);
infile >> horo
>> info.birthDate.day
>> temp
>> info.birthDate.month
>> temp
>> info.birthDate.year;
infile >> info.no;
for(int i=0; i < info.no ;i++)
{
infile.getline(info.wishMessage[i], MAX);
}
infile.close();
cout << "Successfully readed!" << endl;
}
void getHoroNum(char horo[], Student& info)
{
if (strcmp (horo,"Aquarius"))
{
info.birthDate.sign = Aquarius;
}
else if (strcmp(horo,"Pisces"))
{
info.birthDate.sign = Pisces;
}
else if (strcmp(horo,"Aries"))
{
info.birthDate.sign = Aries;
}
else if (strcmp(horo,"Taurus"))
{
info.birthDate.sign = Taurus;
}
else if (strcmp(horo,"Gemini"))
{
info.birthDate.sign = Gemini;
}
else if (strcmp(horo,"Cancer"))
{
info.birthDate.sign = Cancer;
}
else if (strcmp(horo,"Leo"))
{
info.birthDate.sign = Leo;
}
else if (strcmp(horo,"Virgo"))
{
info.birthDate.sign = Virgo;
}
else if (strcmp(horo,"Libra"))
{
info.birthDate.sign = Libra;
}
else if (strcmp(horo,"Scorpio"))
{
info.birthDate.sign = Scorpio;
}
else if (strcmp(horo,"Sagittarius"))
{
info.birthDate.sign = Sagittarius;
}
else if (strcmp(horo,"Capricorn"))
{
info.birthDate.sign = Capricorn;
}
}
void checkHoro (char fHoro[], Student info)
{
if (info.birthDate.sign == Aquarius)
{
fHoro = "Aquarius";
}
else if (info.birthDate.sign == Pisces)
{
fHoro = "Pisces";
}
else if (info.birthDate.sign == Aries)
{
fHoro = "Aries";
}
else if (info.birthDate.sign == Taurus)
{
fHoro = "Taurus";
}
else if (info.birthDate.sign == Gemini)
{
fHoro = "Gemini";
}
else if (info.birthDate.sign == Cancer)
{
fHoro = "Cancer";
}
else if (info.birthDate.sign == Leo)
{
fHoro = "Leo";
}
else if (info.birthDate.sign == Virgo)
{
fHoro = "Virgo";
}
else if (info.birthDate.sign == Libra)
{
fHoro = "Libra";
}
else if (info.birthDate.sign == Scorpio)
{
fHoro = "Scorpio";
}
else if (info.birthDate.sign == Sagittarius)
{
fHoro = "Sagittarius";
}
else if (info.birthDate.sign == Capricorn)
{
fHoro = "Capricorn";
}
}
void getMth (int month, char mth[] )
{
switch (month)
{
case 1:
{
mth = "January";
break;
}
case 2:
{
mth = "February";
break;
}
case 3:
{
mth = "March";
break;
}
case 4:
{
mth = "April";
break;
}
case 5:
{
mth = "May";
break;
}
case 6:
{
mth = "June";
break;
}
case 7:
{
mth = "July";
break;
}
case 8:
{
mth = "August";
break;
}
case 9:
{
mth = "September";
break;
}
case 10:
{
mth = "October";
break;
}
case 11:
{
mth = "November";
break;
}
case 12:
{
mth = "December";
break;
}
}
}
void printOut(Student info, char mth[], char fHoro[])
{
cout << "My name is " << info.name << endl;
cout << "My nationality is " << info.nationality << endl;
cout << "My date of birth is " << info.birthDate.day
<< " " << mth << " "
<< info.birthDate.year << endl;
cout << "I am a" << fHoro << endl;
cout << "\nI have " << info.no << " wishes:" << endl;
for(int i=0; i < info.no ;i++)
{
cout << i << ". " << info.wishMessage[i];
}
}
You have this function definition:
void getHoroNum(char horo[], Student& info)
and before you have this declaration:
void getHoroNum(char , Student&);
latter should be replaced by:
void getHoroNum(char* , Student&);
Related
Why isn't my program doing anything at all?
I'm sorry for the vague title, but I don't know what else to say. Here is my program: #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <fstream> #include <vector> using namespace std; int main (int argc, char **argv) { //string fin; string ttl, dscp, ext; string west = "w"; string east = "e"; string north = "n"; string south = "s"; int numRooms; //string argv[1] = filename; class Room { public:string title; string description; string exits; int exitWest = -1; int exitNorth = -1; int exitEast = -1; int exitSouth = -1; int numExits; }; ifstream fin; fin.open (argv[1]); //cin.ignore(); int t = 0; while (fin) { string tilde; string tester; tester = "~"; cin >> tilde; if (tilde == tester) { t = t + 1; } (numRooms = t / 3); } Room *roomArrayPtr = new Room[numRooms]; fin.clear (); while (fin) { for (int l = 0; l < numRooms; l++) { getline (fin, ttl, '~'); roomArrayPtr[l].title = ttl; getline (fin, dscp, '~'); roomArrayPtr[l].description = dscp; getline (fin, ext, '~'); stringstream sin; sin << ext; string x; int y; while (sin >> x >> y) { if (x == west) { roomArrayPtr[l].exitWest = y; } if (x == south) { roomArrayPtr[l].exitSouth = y; } if (x == north) { roomArrayPtr[l].exitNorth = y; } if (x == east) { roomArrayPtr[l].exitEast = y; } } sin.clear (); int numext; numext = (ext.size ()) / 3; roomArrayPtr[l].numExits = numext; }} //(read in file again populate roomarrayptr w while loop and getline) //roomArrayPtr[index].title = line; //roomArrayPtr[index].description=line; //close files, while loop that reads in user input from stdin, delete pointers w (delete[] roomArrayPtr;) //if (exitsarray[i].size() > 2){ char command; char newcommand; cout << ">"; cin >> command; int currentroom = 0; int newroom; bool keepgoing = true; //string dir1; while (keepgoing) switch (command) { // stringstream ss; case 'l': cout << roomArrayPtr[currentroom].title << endl; cout << roomArrayPtr[currentroom].description << endl; cout << endl; //if (roomArrayPtr[currentroom].numExits < 2) { cout << "Exits: "; if (roomArrayPtr[currentroom].exitWest > -1) { cout << "w"; } if (roomArrayPtr[currentroom].exitNorth > -1) { cout << "n"; } if (roomArrayPtr[currentroom].exitSouth > -1) { cout << "s"; } if (roomArrayPtr[currentroom].exitEast > -1) { cout << "e"; } /*else { cout << "Exits: " ; for (int k = 0; k < numExits; k++){ cout << exitdirection << " "; } }*/ //string newcommand; cin >> newcommand; //int newroom; switch (newcommand) { case 'w': if (roomArrayPtr[currentroom].exitWest == -1) { cout << "You can't go WEST!" << endl; } else { newroom = roomArrayPtr[currentroom].exitWest; cout << "You moved WEST." << endl; } break; case 'e': if (roomArrayPtr[currentroom].exitEast == -1) { cout << "You can't go EAST!" << endl; } else { newroom = roomArrayPtr[currentroom].exitEast; cout << "You moved EAST." << endl; } break; case 'n': if (roomArrayPtr[currentroom].exitNorth == -1) { cout << "You can't go NORTH!" << endl; } else { newroom = roomArrayPtr[currentroom].exitNorth; cout << "You moved NORTH." << endl; } break; case 's': if (roomArrayPtr[currentroom].exitSouth == -1) { cout << "You can't go SOUTH!" << endl; } else { newroom = roomArrayPtr[currentroom].exitSouth; cout << "You moved SOUTH." << endl; } break; } break; case 'q': keepgoing = false; return 0; break; currentroom = newroom; } } Whenever I run it, it compiles, but nothing happens. I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up. What's going on? I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up.
you are reading the wrong file int t = 0; while (fin) { string tilde; string tester; tester = "~"; cin >> tilde; <<<<===== i assume you mean fin if (tilde == tester) { t = t + 1; } (numRooms = t / 3); }
Error Throwing not working to how I wanted it
#include <cstring> #include <string> #include <cstdlib> #include <ctype.h> using namespace std; const int MAX = 100; class SampleEx{ public: SampleEx(int, char); void setNum(int); int getNum(); void setCh(char); char getCh(); private: int number; char c; }; SampleEx :: SampleEx (int n, char c) { this->number =n; this->c = c; } void SampleEx::setNum(int n){number = n;} int SampleEx::getNum(){return number;} void SampleEx::setCh(char n){c = n;} char SampleEx::getCh(){return c;} char Read (char[]); void analyze(char[], int char_loc, int & size); void DigitProcess(char[], int char_loc, int & size); void AlphaProcess(char[], int char_loc, int & size); void printStatus(int status); int nextSpace(char[], int char_loc, int & size); int main() { int status = 0, char_loc = 0, size = 0; char cont = ' '; char lexeme[MAX]; char next = ' '; do { try { do { next = Read(lexeme); cout << lexeme; analyze(lexeme, char_loc, size); } while (next !='\n'); } catch (SampleEx &e) { // cout << "Exception Number: " << e.getNum() << " Char: " << e.getCh() << '\n'; switch(e.getNum()) { case 1: cout << "[Invalid Integer: " << e.getCh() << " Found.] "; break; case 2: cout << "[Invalid Decimal: " << e.getCh() << " Found.] "; break; case 3: cout << "[Invalid Decimal: " << "Too Many . Found.] "; break; case 4: cout << "[Invalid ID: " << e.getCh() << " Found.] "; break; } } cout << endl << "Continue? Y] Yes N] No" << endl; cin.ignore(size); cin >> cont; while (cont != 'Y' && cont != 'N') { cout << "Invalid Input. Try Again." << endl; cin >> cont; } if (cont == 'Y') { cin.ignore(); } } while(cont != 'N'); cout << "Program Ended." << endl; return 0; } void analyze(char item[], int char_loc, int & size) { SampleEx s1(0, ' '); if (isdigit(item[0])) { DigitProcess(item, char_loc, size); } else if (isalpha(item[0])) { AlphaProcess(item, char_loc, size); } else if (item[0] == '.') { s1.setCh(item[0]); s1.setNum(2); throw s1; } else { s1.setCh(item[0]); s1.setNum(4); throw s1; } } char Read(char temp[]) { char extra; int size = 0; cin.get(extra); while (size < MAX && extra != ' ' && extra != '\n') { temp[size] = extra; cin.get(extra); size++; } temp[size] = '\0'; return extra; } void DigitProcess(char item[], int char_loc, int & size) { SampleEx error(0, ' '); size = strlen(item); bool decimalMax = false, alphaUsed = false; for (char_loc = 1; char_loc < size; char_loc++) { if (isdigit(item[char_loc])) { continue; } else if (isalpha(item[char_loc])) { error.setCh(item[char_loc]); error.setNum(1); throw error; alphaUsed = true; break; } else if (item[char_loc] == '.') { if (decimalMax == true) { error.setCh(item[char_loc]); error.setNum(3); throw error; } decimalMax = true; // stops anymore decimals from being entered } else { error.setCh(item[char_loc]); error.setNum(4); throw error; } } if (decimalMax == true && alphaUsed == false) { printStatus(1); } else if (decimalMax == false && alphaUsed == false) { printStatus(2); } } void AlphaProcess(char item[], int char_loc, int & size) { SampleEx error(0, ' '); size = strlen(item); bool digitUsed = false, deciUsed = false; for (char_loc = 1; char_loc < size; char_loc++) { if (isalpha(item[char_loc])) { continue; } else if (isdigit(item[char_loc])) { digitUsed = true; error.setCh(item[char_loc]); error.setNum(4); throw error; for (int i = char_loc; i < size; i++) { if (isspace(item[i])) { char_loc = i - 1; break; } } } else if (item[char_loc] == '.') { deciUsed = true; error.setCh(item[char_loc]); error.setNum(4); throw error; break; } else { error.setCh(item[char_loc]); error.setNum(4); throw error; } } if (digitUsed == false && deciUsed == false) { printStatus(3); } } void printStatus(int status) { switch(status) { case 1: cout << "Decimal "; break; case 2: cout << "Integer "; break; case 3: cout << "ID "; } } The above code will give "ID" if I were to say something like x or mike, "Decimal" if I were to say something like 4.4424, "Integer" if I were to say like 444. However, it will print an error if anything is invalid, like if I put .333, it should print an error. The issue is that the program refuses to print multiple errors at a time. For example: if I were to put "taco taco taco", it should print ID ID ID. but if I were to put taco taco taco1, it would print ID ID [Invalid ID: 1 found] The problem is that if I were to put taco taco1 taco1, it would NOT print the following: ID [Invalid ID: 1 found] [Invalid ID: 1 found] which that is the goal.
How to read txt files into an array that are stored into class variables? [duplicate]
This question already has answers here: Reading file into array of struct c++ (3 answers) C++ Reading text file with delimiter into struct array (2 answers) C++ Reading data from text file into array of structures (2 answers) How do I read data from a text file into an array of struct (1 answer) Reading data from a text file into an array of structs (1 answer) Closed 2 years ago. #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; class BasketballPlayer { public: void printBasketballPlayer() const; BasketballPlayer(); //Constructor with Parameters private: string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; }; class BasketballTeam { public: string name; void printBasketballTeam() const; bool findPlayer(string &); void editPlayer(bool&); BasketballTeam(); //Default Constructor void getName() { getline(cin, name); } private: //void BasketballPlayer(); string name; float MinutesPlayed; float PlayerScoreEffRating; float Steals; float AST; float PointPerGame; float Rebounds; float FieldGoal; float FreeThrow; float ThreePointers; float BLK; float TurnOver; string myArray[16][11]; string PlayerName[15]; float myArray[15][11]; void Team() { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; } } } }; int main() { BasketballPlayer Play; string Search; bool isPlayerThere; char Change; BasketballTeam Team; cout << " Welcome to the Brooklyn Net's Stats and DataBase " << endl; cout << " These are the stats of our new SuperStar " << endl; Play.printBasketballPlayer(); cout << " < Would you Like to Update stats of the roster > --> Y or --> N " << endl; cin >> Change; cout << endl; if (Change == 'Y' || 'y') { Team.findPlayer(Search); Team.editPlayer(isPlayerThere); } else { Team.printBasketballTeam(); } Team.printBasketballTeam(); return 0; }//end main void BasketballPlayer::printBasketballPlayer() const { cout << "|| The players name || " << this->name; cout << endl; cout << "|| Minutes Per Game || " << this->MinutesPlayed; cout << endl; cout << "|| Turnovers Per Game || " << this->TurnOver; cout << endl; cout << "|| Points Per Game || " << this->PointPerGame; cout << endl; cout << "|| Rebounds Per Game || " << this->Rebounds; cout << endl; cout << "|| Asists Per Game || " << this->AST; cout << endl; cout << "|| Blocks Per Game || " << this->BLK; cout << endl; cout << "|| 3 Point % || " << this->ThreePointers; cout << endl; cout << "|| Free-Throw % || " << this->FreeThrow; cout << endl; cout << "|| Field Goal %|| " << this->FieldGoal; cout << endl; cout << "|| Steals % || " << this->Steals; cout << endl; cout << "|| Player Scoreing Effiencey Rating || " << this->PlayerScoreEffRating; cout << endl; } BasketballPlayer::BasketballPlayer() //Constructor with Parameters { name = "James Harden"; MinutesPlayed = 40.2f; TurnOver = 4.2f; PointPerGame = 24.1f; Rebounds = 8.1f; AST = 12.0f; BLK = 0.6f; ThreePointers = 37.9f; FreeThrow = 89.2f; FieldGoal = 48.2f; Steals = 1.1f; PlayerScoreEffRating = 1.561f; } void BasketballTeam::printBasketballTeam() const { ifstream file("TextFileTeam.txt"); if (file.is_open()) { string myArray[16]; for (int i = 0; i < 16; ++i) { file >> myArray[i]; cout << myArray[i]; cout << endl; } } } bool BasketballTeam::findPlayer(string&) { bool Finder = false; const char *name; switch (*name) { case 1: if(name == "Kevin_Durant") Finder = true; break; case 2: if (name == "Kyrie_Irving") Finder = true; break; case 3: if (name == "James_Harden") Finder = true; break; case 4: if (name == "Joe_Harris") Finder = true; break; case 5: if (name == "Jarrett_Allen") Finder = true; break; case 6: if (name == "Jeff_Green") Finder = true; break; case 7: if (name == "Taurean_Prince") Finder = true; break; case 8: if (name == "Timothe_Luwawu - Cabarrot") Finder = true; break; case 9: if (name == "Spencer_Dinwiddie") Finder = true; break; case 10: if (name == "DeAndre_Jordan") Finder = true; break; case 11: if (name == "Bruce_Brown_Jr.") Finder = true; break; case 12: if (name == "Landry_Shamet") Finder = true; break; case 13: if (name == "Chris_Chiozza") Finder = true; break; case 14: if (name == "Reggie_Perry") Finder = true; break; case 15: if (name == "Tyler_Johnson") Finder = true; break; default: cout << " Player not in Roster " << endl; break; } return Finder; } void BasketballTeam::editPlayer(bool &) { int editValue; BasketballTeam Team; bool isThere; ifstream file("JustData.txt"); if (file.is_open()) { string myArray[15]; for (int i = 0; i < 15; ++i) { file >> myArray[i]; } } if (isThere == true) { cout << " What would you like to edit? " << endl; cout << "[1] Mintues, [2] Turnover, [3] Points Per Game, [4] Rebounds Per Game, [5] Steals Per Game, [6] Free Throw %, [7] Assits Per Game, [8] Filed Goal %" << endl; cout << "[7] Assits Per Game, [8] Filed Goal %[9] 3P%, [10] Player Scoring Eff, [11] Blocks Per Game ---> "; cin >> editValue; switch (editValue) { case 1: MinutesPlayed = editValue; break; case 2: PlayerScoreEffRating = editValue; break; case 3: PointPerGame = editValue; break; case 4: Rebounds = editValue; break; case 5: Steals = editValue; break; case 6: FreeThrow = editValue; break; case 7: AST = editValue; break; case 8: FieldGoal = editValue; break; case 9: ThreePointers = editValue; break; case 10: PlayerScoreEffRating = editValue; break; case 11: BLK = editValue; break; default: break; } } } BasketballTeam::BasketballTeam() //Default Constructor { int j; int row; int col; j = 0; ifstream file("JustData.txt"); if (file.is_open()) { float PlayerArray[15][11]; for (int row = 0; row < 15; row++) { for (int col = 0; col < 11; col++) { file >> PlayerArray[row][col]; MinutesPlayed = PlayerArray[j][col]; TurnOver = PlayerArray[j][col]; Rebounds = PlayerArray[j][col]; PointPerGame = PlayerArray[j][col]; AST = PlayerArray[j][col]; BLK = PlayerArray[j][col]; ThreePointers = PlayerArray[j][col]; FreeThrow = PlayerArray[j][col]; FieldGoal = PlayerArray[j][col]; Steals = PlayerArray[j][col]; PlayerScoreEffRating = PlayerArray[j][col]; j++; } } } ifstream file2("JustNames.txt"); if (file2.is_open()) { string PlayerName[15]; for (int row = 0; row < 15; row++) { file >> PlayerName[row]; name = PlayerName[row]; } } }; JustData.txt 36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 JustNames.txt Kevin_Durant Kyrie_Irving James_Harden Joe_Harris Jarrett_Allen Jeff_Green Taurean_Prince Timothe_Luwawu-Cabarrot Spencer_Dinwiddie DeAndre_Jordan Bruce_Brown_Jr. Landry_Shamet Chris_Chiozza Reggie_Perry Tyler_Johnson TeamNoTitle.txt Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 Bruce_Brown_Jr.,17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 TeamFileNets.txt Player,MPG,TOV,RPG,APG,SPG,BPG,PPG,FG%,3P%,FT%,SC-EFF Kevin_Durant,36.9,3.5,7.5,5.2,0.8,1.4,30.8,53.3,45.2,87.8,1.575 Kyrie_Irving,35.8,2.3,4.8,5.7,1,0.8,28.3,53.5,44.7,94.8,1.403 James_Harden,40.3,4.2,8.1,12,1.1,0.6,24.1,48.2,37.9,89.2,1.561 Joe_Harris,31.7,0.9,3.7,2.1,0.6,0.3,14.9,51.2,48.7,61.5,1.361 Jarrett_Allen,26.6,1.8,10.4,1.7,0.6,1.6,11.2,67.7,0,75.4,2.062 Jeff_Green,25.7,1,3.8,1.4,0.7,0.2,8.9,54.1,44.7,83.3,1.519 Taurean_Prince,18.1,0.9,2.8,0.6,0.7,0.7,8.1,40.5,35.1,88.9,1.311 Timothe_Luwawu-Cabarrot,19,0.6,2.2,1.3,0.6,0.2,7.3,38.3,36.3,72.2,1.091 Spencer_Dinwiddie,21.4,1.7,4.3,3,0.7,0.3,6.7,37.5,28.6,100,1.25 DeAndre_Jordan,20.3,1.6,6.9,1.7,0.3,1.4,6.6,81.3,0,48.4,1.813 "Bruce_Brown_Jr.",17.6,0.9,4.2,0.9,0.5,0.4,5.9,58.8,17.6,71.4,1.329 Landry_Shamet,17.2,0.8,1.4,1.1,0.6,0.2,5.6,34.4,29.6,84,1.14 Chris_Chiozza,11.2,0.8,1,2.5,0.5,0.4,4,28.2,29.4,71.4,0.821 Reggie_Perry,10.5,0.8,3.6,0.9,0.1,0.4,3.6,41.2,16.7,66.7,0.98 Tyler_Johnson,6.2,0.3,0.7,1.1,0.4,0,1.3,30,42.9,0,0.9 I'm sure that I'm not understanding Classes. Trying to use fstream to hold data of players so that my classes and driver code can change those files then display data from stored data in classes. I have no syntax errors but code not running. Most likey because of me reading file into array wrong to get data into my classes from file and improper calling of classes in main function.
program crashes after when trying to load the csv file
me again. I have a problem. I tried to run this code and when I compile it, the compiler shows no errors, but after running it, the program crashes. HELP!!! What the program should do: It searches trough the data of deseases and desease codes of the WHO ( World Health Organisation). Two csv files are given (english and german version) and you have a choice to search in english and in german. I think that the program chrashes when it tries to load the char*-s from the csv file. It's driving me crazy. Here is also the link where you can find the whole project: LINK Code: #include <iostream> #include <stdlib.h> #include <cstring> #include <iomanip> #include <fstream> #include <list> #include <algorithm> using namespace std; enum KEY {code, disease} key; enum LANGUAGE {english, deutsch} language; char* buffer; struct lst { char *_code; char *_disease; }; streamsize _buffer = 10000; bool isPartOf(char* word, char* sentence) { unsigned int i=0; unsigned int j=0; for(;i < strlen(sentence); i++) { if(sentence[i] == word[j]) { j++; } } if(strlen(word) == j) return true; else return false; } void printList(list<lst>* LST) { for(list<lst>::iterator i= LST->begin(); i != LST->end(); i++) { cout << i->_code << '\t' << i->_disease << endl; } } list<lst>* makeList(char* fileName) { int i,j; fstream ICDcsv; ICDcsv.open(fileName); list<lst>* new_list = new list<lst>; if(ICDcsv.is_open()) { while(ICDcsv) { lst* x = new lst; ICDcsv.getline(buffer,_buffer); i = 0; j = 0; while (buffer[i] != ';') { x->_code[i] = buffer[i]; i++; } i++; while (buffer[i] != ';') { x->_disease[j] = buffer[i]; i++; j++; } (*new_list).push_back(*x); } ICDcsv.close(); } else{cerr << "Error: file error" << endl;} return new_list; } list<lst>* listSearch(list<lst> *LST,char* wrd,KEY key) { switch(key) { case code: for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++) { if(!isPartOf(wrd, ( *i )._code)) { delete [] i->_code; delete [] i->_disease; delete &(*i); } } //i-> break; case disease: for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++) { if(!isPartOf(wrd, ( *i )._disease)) { delete [] i->_code; delete [] i->_disease; delete &(*i); } } break; } return LST; } int main() { int choice; int program_end=1; char* _file; char* Search; cout << "World Health Institution (WHO)/Weltgesundheitsorganisation" << endl; cout << "International Statistical Classification of Diseases and Related Healt Problems (ICD)/Internationale statistische Klassifikation der Krankheiten und verwandter Gesundheitsprobleme" << endl; cout << "1 english" << endl; cout << "2 deutsch" << endl; cout << "your choice/Ihre Auswahl: "; cin >> choice; cin.clear(); if(choice == 1) language = english; else language = deutsch; switch (language) { case english: { _file = "care_icd10_en.csv"; break; } case deutsch: { _file = "care_icd10_de.csv"; break; } } cout << "0 end/Ende" << endl; cout << "1 search for ICD code (e.g. K52.9)/Suche nach ICD Kode (Beispiel K52.9)" << endl; cout << "2 search for desease (e.g. Ebola)/Suche nach Krankheit (Beispiel Ebola)" << endl; cout << "your choice/Ihre Auswahl: "; cin >> program_end; cin.clear(); switch(program_end) { case 0: break; case 1: key = code; cout << "to search for ICD code/zu suchender ICD Kode: "; break; case 2: key = disease; cout << "to search for deseade/zu suchende Krankheit: "; break; } if(program_end != 0) { cin >> Search; list<lst>* test = makeList(_file); list<lst>* test2 = listSearch(test,Search,key); printList(test); } return 0; }
_block_type_is_valid phead- nblockuse on delete command
So I know this is a pretty common error, but I'm very new to C++, we are using it for a programing languages class, and this error has me stuck. The delete parser; line is the line that causes this error, and I cannot figure out why. Turtle2.cpp #include <iostream> #include <sstream> #include <string> #include <fstream> #include "scanner.h" #include "parser.h" using namespace std; int main(int argc, char* argv[]) { //string line; if (argc != 2) { cout << "Usage: turtle filename" << endl; return 0; } char* filename = argv[1]; cout << "filename is " << filename << endl; ifstream in(filename); Parser * parser = new Parser(&in); AST* tree = parser->parse(); tree->evaluate(); delete tree; delete parser; //This is the line that causes the error! return 0; } parser.cpp #include "parser.h" #include "calcex.h" #include <string> #include <sstream> Parser::Parser(istream* in) { scan = new Scanner(in); } Parser::~Parser() { try { delete scan; } catch (...) { } } AST* Parser::parse() { AST* returnValue = Prog(); cout << "We are still ok1" << endl; return returnValue; } AST* Parser::Prog() { AST* result = StmtList(); Token* t = scan->getToken(); if (t->getType() != eof) { cout << "Syntax Error: Expected EOF, found token at column " << t->getCol() << endl; throw ParseError; } cout << "We are still ok2" << endl; return result; } AST* Parser::StmtList() { AST* result = Statement(); Token* t = scan->getToken(); scan->putBackToken(); if (t->getType() != eof) { AST* result = StmtList(); return result; } return result; } AST* Parser::Statement() { float num1; float num2; stmtNode* node; Token* t = scan->getToken(); /*if (turtle->getType() != keyword || turtle->getLex() != "turtle"){ cerr <<"expected turtle" << endl; //print to standard error stream throw ParseError; }*/ if (t->getType() == keyword && t->getLex() == "turtle"){ t = scan->getToken(); if (t->getType() == dot){ t = scan->getToken(); if (t->getType() == keyword && t->getLex() == "goto"){ t = scan->getToken(); if (t->getType() == lparen){ t = scan->getToken(); if (t->getType() == number){ istringstream in(t->getLex()); in >> num1; t = scan->getToken(); if (t->getType() == comma){ t = scan->getToken(); if (t->getType() == number){ istringstream in(t->getLex()); in >> num2; t = scan->getToken(); if (t->getType() == rparen){ cout << "Good" << endl; node = new stmtNode(num1,num2); cout << "X is " << node->getX() << endl; cout << "Y is " << node->getY() << endl; } } } } } } } } else{ cout << "bad" << endl; } return node; } scanner.cpp #include "scanner.h" #include "calcex.h" #include <iostream> #include <string> using namespace std; //Uncomment this to get debug information //#define debug const int numberOfKeywords = 2; const string keywd[numberOfKeywords] = { //defining the keywords string("turtle"), string("goto") }; int isLetter(char c) { //c is bigger or equal to 'a' and small or equal to 'z'. same for captial versions return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); } int isDigit(char c) { //c is bigger or equal to '0' or smaller or equal to '9' return (c >= '0' && c <= '9'); } int isWhiteSpace(char c) { //c is a space, tab or newline return (c == ' ' || c == '\t' || c == '\n'); } Scanner::Scanner(istream* in): //scanner constructor inStream(in), lineCount(1), colCount(0), needToken(true), lastToken(0) {} Scanner::~Scanner() { //scanner de-constructor try { delete inStream; } catch (...) {} } void Scanner::putBackToken() { //method? needToken = false; } Token* Scanner::getToken() { //method? if (!needToken) { needToken=true; return lastToken; } Token* t; int state=0; bool foundOne=false; char c; string lex; TokenType type; int k; int column, line; c = inStream->get(); while (!foundOne) { colCount++; switch (state) { case 0 : lex = ""; column=colCount; line = lineCount; if (isLetter(c)) state=1; else if (isDigit(c)) state=2; else if (c=='.') state=3; else if (c==',') state=4; else if (c=='(') state=5; else if (c==')') state=6; else if (c=='\n') { colCount=0; lineCount++; } else if (isWhiteSpace(c)); else if (inStream->eof()) { foundOne=true; type=eof; } else { cout << "Unrecognized Token found at line " << line << " and column " << column << endl; throw UnrecognizedToken; } break; case 1 : if (isLetter(c) || isDigit(c)) state=1; else { for (k=0;k<numberOfKeywords;k++) if (lex == keywd[k]) { foundOne = true; type = keyword; } if (!foundOne) { type = identifier; foundOne = true; } } break; case 2 : if (isDigit(c)) state=2; else { type = number; foundOne=true; } break; case 3 : type = dot; foundOne = true; break; case 4 : type = comma; foundOne = true; break; case 5 : type = lparen; foundOne=true; break; case 6 : type = rparen; foundOne=true; break; } if (!foundOne) { lex = lex + c; c = inStream->get(); } } inStream->putback(c); colCount--; if (type == number || type == identifier || type == keyword) { t = new Token(type,new string(lex),line, column); } else { t = new Token(type,new string(lex),line,column); } #ifdef debug cout << "just found " << lex << " with type " << type << endl; #endif lastToken = t; return t; } I don't know if that is enough code to help you guys out or not, if you need anything more just ask, its not a secret or anything :) I know its the de-constructor for parser, but I have no idea how to fix it, or really why this is happening... I've added scanner.cpp, because some ponited out that the problem could be in its deconstructor, so I hope that helps.
The reason why this is failing is that you are using delete on something that was allocated on the stack. Note the combination of ifstream in(filename);, creating an ifstream on the stack and the delete inStream; in the destructor of Scanner. The easiest suggestion would be to allocate in on the heap, whish ifstream *in = new ifstream(filename) or whatnot. A better solution would probably be to have the other classes(Scanner, Parser, etc) take the ifstream by reference, and avoid pointers unless they are needed.
You are trying to delete a stack variable, in the destructor of Scanner. Parser * parser = new Parser(&in); Parser::Parser(istream* in) { scan = new Scanner(in); } Parser::Parser(istream* in) { scan = new Scanner(in); } Parser::~Parser() { try { delete scan; } catch (...) { } } Scanner::~Scanner() { //scanner de-constructor try { delete inStream; } catch (...) {} }