C++ String Array to Text Document - c++

I am trying to create a program that will make an array of data entered until a stop commands is entered and have it log it into a text document. I am getting a crash of Microsoft Visual Studio after i enter the Fist name and Last name fields.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
int main(void) {
string firstName;
string lastName;
string stream;
int outputString;
string dataOutput;
string dataArray[1];
bool askData = true;
int i = 0;
ofstream outfile("data.txt");
while (askData) {
cout << "Type First then Last Name or \"$Stop\" to save and exit" << "\n" << "First: ";
getline(cin, firstName);
if (firstName == "$Stop") {
askData = false;
}
else {
cout << "Last: ";
cin >> lastName;
cout << "\n\n\n";
dataOutput = firstName + " " + lastName + "; ";
dataArray [1 + i] = dataOutput;
i++;
}
cout << dataOutput;
}
outfile << dataArray;
outfile.close();
return 0;
}
EDIT:
Also tried.
string dataArray[];
then later assigning it to an incrementing variable.
int i = 0;
dataArray[i];
i++;
Can you tell me why this doesnt work?

Related

Why is the data in the "addtocart()" function not written into the file ? c++

In this program I'm trying to add data about customers in a file. However, for some reason when I open the file I can only see the data from the "newcustomer()" function. Can somebody tell me the reason for this please.
Here's the related part of my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct cartitem{
string name;
int num_of_copies;
float price;};
int i;
int ci=0;
fstream customersdata;
void newcustomer(fstream &customersdata, string cname){
string arrtime;
customersdata << "Name: " << cname << '\n';
string order = cname+"order";
customersdata << order <<'\n';}
void addtocart(fstream &customersdata, string cname){
ci++;
string bname;
cout << "enter book name \n" ; cin >> bname;
int num_of_copies;
cout << "enter number of copies to add to cart \n" ; cin >> num_of_copies;
string order = cname+"order";
cartitem x;
x.name = bname;
x.num_of_copies=num_of_copies;
if(customersdata.is_open()){
string b;
while (getline(customersdata,b)){
if (b.find(order, 0) != string::npos){
size_t pos;
pos = b.find(order, 0);
customersdata.seekp(pos+ci);
customersdata << "item" << ci << ": " << x.name << " num of copies: " << x.num_of_copies <<'\n';}}}
else { cout << "unable to open file\n";}}
int main(){
string cname;
customersdata.open("customersdata.txt", ios::out | ios::in);
cout << "enter customer name\n"; cin >> cname;
newcustomer(customersdata,cname);
addtocart(customersdata,cname);
customersdata.close();
string filename = "customersdata.txt";
system(filename.c_str());}
that's what the file looks like if I run a test code for a person named james

Error on getline function no instance matches the arguments

Why my code is not executing and showing me error ?? Im getting error on this line
while (getline(s, word, ' , '))
my Code is below:
#include <fstream>
#include <string>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// first we define a class that will represent all the candidates
class Candidate
{
string name;
int votes;
public:
Candidate()
{
name = "";
int votes = 0;
}
Candidate(string cand_name, int vote_count)
{
name = cand_name; votes = vote_count;
} string getName() { return name; } int getVotes() { return votes; } void get_details() { cout << name << ", " << votes << endl; }
//Following member method is used to increment the vote count
void vote_this_candidate() { votes++; }
};
int main()
{
cout << "Welcome to Student President Voting System!!!" << endl;
Candidate allCandidates[100];
int totalVotes = 0;
// File pointer fstream fin; // Open an existing file
fstream fin;
fin.open("candidantes.txt", ios::in); // Read the Data from the file // as String Vector
vector <string> row;
string line, word, temp; int index = 0; // Following while loop will iterate for each line in the file
while (fin >> temp) {
row.clear(); // read an entire row and // store it in a string variable 'line'
getline(fin, line); // used for breaking words
string s(line); // read every column data of a row and // store it in a string variable, 'word'
while (getline(s, word, ' , '))
{ // adding the splitted words to row
row.push_back(word);
} allCandidates[index] = Candidate(row[0], stoi(row[1])); totalVotes += stoi(row[1]); index++;
}
string name = ""; cout << "\nPlease enter the name of the candidante you want to vote : ";
getline(cin, name); int cand_no = -1; string userChoice; int i = 0; //Now we find the candidante with the same inputted name
while (i < index) {
if (allCandidates[i].getName() == " " + name) {
cand_no = i; cout << "Do you want to vote this candidante [y/n] : ";
cin >> userChoice; //After finding the candidate just ask the user to vote the candidante
if (userChoice == "y") { //to vote just call the member method that increments the vote count
allCandidates[cand_no].vote_this_candidate(); totalVotes++; cout << endl << "You successfully voted to " << name << " Thanks for voting!!!" << endl;
}
else { cout << "You didn't vote!!!" << endl; } break;
}
i++;
} if (cand_no == -1) {
cout << "Candidante not found!!! Do you like to add this candidate [y/n]: ";
cin >> userChoice; if (userChoice == "y") { allCandidates[index + 1] = Candidate(name, 1); totalVotes++; index++; }
}
//To show top five candidates we first sort the array with lambda
std::sort(allCandidates, allCandidates + 10, [](Candidate a, Candidate b) -> bool { return a.getVotes() > b.getVotes(); });
//then we show only first five candidates
cout << endl << "These are top 5 candidantes so far : " << endl;
for (int i = 0; i < 5; i++)
{
cout << i + 1 << ","; allCandidates[i].get_details();
} cout << endl << "Total studnets voted: " << totalVotes;
}
Problem is here:
string s(line);
while (getline(s, word, ' , '))
because getline has no overload that takes a std::string as its first parameter.
However, there is an overload that takes a stringstream, so you can do:
stringstream ss(line);
while (getline(ss, word, ' , '))
Also, ' , ' won't do what you think. Perhaps you meant ','.
Finally, int votes = 0; in your Candidate() constructor should just be votes = 0;. As it is, you are just declaring, initialising and then discarding a local variable.
The problem is that the compiler is telling you that the parameters you've given don't match a definition of the function. In your case I believe the problem is that you've given it 3 characters instead of 1 in the character portion (remember, a space is also a character). Try changing ' , ' to ','

Trouble with arrays and structs from input file

I am working on this problem for a college course and I'm unsure why it isn't working. I thought I had everything setup correctly, but when I try running the program the file won't open on the first attempt at inputting the file name and when I input it again I get an "Exception Thrown" error in the "xmemory" part that I have no idea what any of it means.
The input file that the program is taking data from is just a text file with the following data:
201742 Sponge Bob 82.6
201701 Patrick Star 14.1
201753 Squidward Tentacles 85.43
201744 Sandy Squirrel 75.61
201700 Plankton Plank 100.0
The final output of the program should display the highest and lowest grade with the students first and last name, the average score, and the number of students tested. Any help would be much appreciated.
// Zane Richards
// Lab 10 Q2
// 4/6/2020
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>
using namespace std;
struct student {
int ID;
string firstName;
string lastName;
float grade;
};
void maxGradeFunc(struct student* s, int size)
{
float maxGrade = 0;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade > maxGrade)
{
maxGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << maxGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void minGradeFunc(struct student* s, int size)
{
float minGrade = 999;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade < minGrade)
{
minGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << minGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void avgGradeFunc(struct student* s, int size)
{
float sum = 0;
for (int i = 0; i < size; ++i)
{
sum += s[i].grade;
}
float avg = sum / size;
cout << "Avearge grade is " << avg << endl;
cout << "The total number of students are: " << sum << " students" << endl;
}
int main()
{
ifstream inFile;
string fileName = "";
struct student s[5];
int ID;
string firstName, lastName;
float grade;
int i = 0;
cout << "Please enter the input file name: "; //File is named "Student.txt"
cin >> fileName;
while (!inFile.is_open()) {
cout << "Sorry, the file did not open. \nTry again, or type \"cancel\" to quit: ";
cin >> fileName;
if (fileName == "cancel") {
cout << "Cancelling..." << endl;
break;
}
else {
inFile.open(fileName);
}
}
while (inFile.is_open()) {
inFile >> ID;
s[i].ID = ID;
inFile >> firstName;
s[i].firstName = firstName;
inFile >> lastName;
s[i].lastName = lastName;
inFile >> grade;
s[i].grade = grade;
i++;
}
maxGradeFunc(s, 5);
minGradeFunc(s, 5);
avgGradeFunc(s, 5);
return 0;
}
Here is the error code I'm getting: https://i.stack.imgur.com/i35Oq.png
Figured out the issue, deleted the code that allowed for multiple attempts, and changed it to just open the file and that fixed it. Thanks for the help everyone, much appreciated!

For loop returning process after 2nd iteration

I'm writing code to take a player's name as input, search a csv file for the name and if the file contains the name save the entire row to a vector within a vector to be accessed later. However the process is returned after the 2nd iteration of the for loop (it's supposed to loop 11 times). Any help is appreciated! Here's the code:
[#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include "fantasy.h"
using namespace std;
player::player(void)
{
NULL;
}
void player::playerinput(void)
{
playername = " ";
playern2 = " ";
int count = 0;
fileName = " ";
for(int i=0; i<11; i++){
std::cout << "Enter player second name: ";
std::cin >> playername;
player::opencsv(playername);
}
}
void player::opencsv(string playername){
count = 0;
run = true;
string line, word, temp;
vector<string> row = {};
fin.open("C:/Users/Desktop/CSProject/cleaned_players 1819.csv", ios::in);
while(run){
row.clear();
getline(fin, line);
stringstream s(line);
while (getline(s, word, ',')){
row.push_back(word);
}
playern2 = row\[1\];
if(playern2 == playername){
count = 1;
players.push_back(row);
std::cout << "Player: " << row\[0\] << " " << row\[1\] << " added to database" << std::endl;
run = false;
return;
}
if(count = 0){
std::cout << "Player not in database" << std::endl;
return;
}
}
row.clear();
fin.clear();
}
int main()
{
player P1;
P1.playerinput();
}
1

Finding a word in C++

I'm able to find the word in my list but I would like to display whatever number there is after the word has been found. My list has names followed by their GPA.
Example...
michael 2.3
Rachel 2.5
Carlos 3.0
I would like to add the feature of displaying the number located after the name once it's found, I declared as int GPA but I'm not sure how to incorporated in my program.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string name;
int offset;
string line;
int gpa;
ifstream read_file;
read_file.open("alpha.dat");
cout << "Please enter your name: \n";
cin >> name;
if (read_file.is_open())
{
while (!read_file.eof())
{
getline(read_file, line);
if ((offset = line.find(name)) != string::npos)
{
cout << "the word has been found: \n";
// cout << name << gpa; example to display
}
}
read_file.close();
return 0;
}
As far as I can tell, you just need to output the line that you read from file:
while( getline(read_file, line) )
{
if ((offset = line.find(name)) != string::npos) cout << line << endl;
}
Note that this isn't the best way to find the name. For example, what if the user enters Carl? It will be found as part of the string Carlos. Or indeed, if they enter 2, it will match parts of the GPA for multiple people.
What you can do here is use a string stream to read the name out. Let's assume it contains no spaces, which would make it conform to how you are reading the user's name in. You need to include <sstream>, by the way. Note that you can read out the GPA as part of this same mechanism.
istringstream iss( line );
string thisname, gpa;
if( iss >> thisname >> gpa ) {
if( thisname == name ) cout << name << " " << gpa << endl;
}
Finally, you may want to consider ignoring case when comparing strings. The cheeky way is to just use the old C functions for this. I know there are C++ methods for this, but none are as simple as good old stricmp from <cstring>:
if( 0 == stricmp(thisname.c_str(), name.c_str()) ) {
cout << name << " " << gpa << endl;
}
You can split line using stringstream, and store it into a vector, like this:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
string name;
int offset;
string line;
int gpa;
ifstream read_file;
read_file.open("alpha.dat");
cout << "Please enter your name: \n";
cin >> name;
if (read_file.is_open())
{
while (!read_file.eof())
{
getline(read_file, line);
if ((offset = line.find(name)) != string::npos)
{
cout << "the word has been found: \n";
stringstream iss(line);
vector<string> tokens;
string str;
while (iss >> str)
tokens.push_back(str);
cout << tokens[0] << tokens[1];
}
}
read_file.close();
return 0;
}
}
You can replace getline(read_file, line)... with:
read_file >> name >> gpa;
if (name == search_name)
cout << name << " " << gpa << endl;