I have a problem with my exercise code. If I enter the name and score value the values aren't getting pushed into the vector. Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
while(true)
{
vector<string> names = {"test"};
vector<int> scores = {0};
string name = "none";
int score = 0;
cin >> name >> score;
if(name == "print" && score == 0)
{
for(int i = 0;i<names.size();++i)
{
cout << "name:" << names[i] << " score:" << scores[i] << "\n";
}
}
if(name == "NoName" && score == 0)
{
break;
}
if (find(names.begin(), names.end(), name) != names.end())
{
cout << name << " found name in names, you can't use this name.\n";
}else{
names.push_back(name);
scores.push_back(score);
}
}
}
the else-statement where the values are getting pushed in the vector is getting called but it doesn't push the values in the vector.
Your issue here is names and scores are declared inside the while loop. That means every iteration they are constructed, used, and then destroyed. This means in every iteration you have fresh vectors. You need to move the vectors out of the loop so they persist through the entire execution of the loop.
vector<string> names = {"test"};
vector<int> scores = {0};
while(true)
{
string name = "none";
int score = 0;
...
}
Related
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 ','
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
This is part of a homework assignment I recently finished. I am required to use an array of structs to store a library of books by title and author. The code is working and running perfectly fine when sorting and displaying author or title alphabetically according to user input.
The only issue I run into is when it shows all books sorted alphabetically. There are 14 books total in the text file used with the assignment, but only 13 books show up when the show all (S) option is entered.
An example of the error would be:
()
Audio for Games (Brandon)
Instead of:
Audio for Games (Brandon)
Beginning LINUX Programming (Stones and Matthew)
My Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;
// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);
int main()
{
// initialised variables
int count = 0;
char selector = 'q', yesNoAnswer = 'n';
string name;
string title;
// asks user for file pathname
cout << "Welcome to Tommy's Library Database." << endl;
cout << "Please enter the name of the file: ";
getline(cin, pathName);
loadData();
count = loadData();
cout << count << " Records loaded successfully." << endl;
// Switch case menu
do {
cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(count, title);
if (count <= 0) {
cout << " No counts found! " << endl;
}
else {
showAll(count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData()
{
int count = 0;
int i = 0;
lib.open(pathName);
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! " << endl;
return -1;
}
while (!lib.eof())
{
getline(lib, books[count].title);
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
}
}
// Sorts by book title.
void sortByTitle(int count, string title) {
Book temp;
for (int i = 0; i < count; i++) {
for (int j = 0; j < count - i; j++) {
if (books[j].title > books[j + 1].title) {
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
The text file im using with the assignment (books.txt)
Objects First with Java
Barnes and Kolling
Game Development Essentials
Novak
The Game Maker's Apprentice
Overmars
C++ Programming: From Problem Analysis...
Malik
C++ Programming Lab Manual
Scholl
Beginning LINUX Programming
Stones and Matthew
C++ Programming: Program Design Including...
D. S. Malik
C++ How to Program
Deitel and Deitel
Programming and Problem Solving with C++
Dale, Weems, Headington
Game Character Development with Maya
Ward
Developing Games in Java
Brackeen
C# Programming
Harvey, Robinson, Templeman, Watson
Java Programming
Farrell
Audio for Games
Brandon
You were starting your loop from 0 inside your showAll() method when your books array starts from 1, just start the loop from 1 and go to count + 1
for (int i = 1; i < count + 1; i++)
Your sort function doesn't work correctly. It's off by one and moves an empty element to the first index. It would cause undefined behavior if your array were full. Your sort function sorts all elements from 0 to count but it should sort from 0 to count - 1. You should fix your sort function (std::sort usually is faster than bubble sort):
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;
// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);
int main()
{
// initialised variables
int count = 0;
char selector = 'q', yesNoAnswer = 'n';
string name;
string title;
// asks user for file pathname
cout << "Welcome to Tommy's Library Database." << endl;
cout << "Please enter the name of the file: ";
getline(cin, pathName);
loadData();
count = loadData();
cout << count << " Records loaded successfully." << endl;
// Switch case menu
do {
cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(count, title);
if (count <= 0) {
cout << " No counts found! " << endl;
}
else {
showAll(count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData()
{
int count = 0;
int i = 0;
lib.open(pathName);
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! " << endl;
return -1;
}
while (!lib.eof())
{
getline(lib, books[count].title);
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
}
}
// Sorts by book title.
void sortByTitle(int count, string title) {
std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
return lhs.title < rhs.title;
});
}
In addition:
You shouldn't read a stream with while (!lib.eof()): Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong?
You can remove the first loadData()
You can remove the second parameter of void sortByTitle(int count)
You are shadowing global variables with local variables, e.g. global ifstream lib and local ifstream lib in int loadData()
You can remove unused variables
You should remove using namespace std;: Why is “using namespace std;” considered bad practice?
You should avoid global variables
You should replace endl by '\n' if you don't need to flush in that moment. endl does more than a simple linebreak and usually it's not necessary.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using std::cin;
using std::cout;
using std::ifstream;
using std::string;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
// global variables
int loadData(string pathName, Book *books);
void showAll(Book *books, int count);
void sortByTitle(Book *books, int count);
int main()
{
// initialised variables
int count = 0;
char selector = 'q';
// asks user for file pathname
cout << "Welcome to Tommy's Library Database.\n";
cout << "Please enter the name of the file: ";
string pathName;
getline(cin, pathName);
Book books[ARRAY_SIZE];
count = loadData(pathName, books);
cout << count << " Records loaded successfully.\n";
// Switch case menu
do {
cout << "\nPlease enter a keyword that corresponds to the list of options: \n";
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(books, count);
if (count <= 0) {
cout << " No counts found! \n";
}
else {
showAll(books, count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData(string pathName, Book *books)
{
int count = 0;
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! \n";
return -1;
}
while (getline(lib, books[count].title))
{
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(Book *books, int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")\n";
}
}
// Sorts by book title.
void sortByTitle(Book *books, int count) {
std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
return lhs.title < rhs.title;
});
}
I have created a function that reads from a text file, adds content to a vector, shows the contacts. Then it prompts the user to choose which contact to remove. The program removes the contact but it removes other contacts as well (not all of them).
Here is the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdio>
#include <iomanip>
using namespace std;
vector<string> contakt;
void deleteContact()
{
ifstream input;
input.open("contacts.txt");
string entry;
int contactID=0;
int index = contactID;
while (getline(input, entry))
{
contakt.push_back(entry);
}
input.close();
cout << "\n\n\nCurrent contacts in list: "<< endl;
if (contakt.size() == 0) cout << "Empty" <<endl;
for (int i = 0; i < contakt.size(); i++)
{
cout << i << ") " << contakt[i] << endl;
}
cout<< " Enter the Id of the contact you would like to remove"<<endl;
cin>> contactID;
if (index != -1)
{
ofstream output;
output.open("temp.txt");
for (vector<string>::iterator it = contakt.begin(); it!= contakt.end(); it++)
{
contakt.erase(contakt.begin() + index);
output<< *it <<'\n';
}
remove("contacts.txt");
rename("temp.txt", "contacts.txt");
output.close();
cout << "Contact deleted succesfull." << endl;
}
else cout << "\nNote: Id was not found in file." <<endl;
return;
}
code here
I remade the function from the beggining and now i am facing another problem.
At the end of the file a blank space is created whenever i remove a contact.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void deleteContact()
{
vector<string> file;
string temp;
ifstream input("contacts.txt");
while( !input.eof() )
{
getline(input, temp);
file.push_back(temp);
}
input.close();
string item;
cout << "Enter an name to delete from the contacts: ";
cin>>item;
int t = 0;
for(int i = 0; i < (int)file.size(); ++i)
{
if(file[i].substr(0, item.length()) == item)
{
file.erase(file.begin() + i);
cout << "Order erased!"<< endl;
i = 0; // Reset search
t++;
}
}
if (t == 0) cout<< "There is no contact with that name!!"<< endl;
ofstream output("contacts.txt", ios::out | ios::trunc);
for(vector<string>::const_iterator i = file.begin(); i != file.end(); ++i)
{
output << *i << '\n';
}
output.close();
return;
}
Your code modifies the vector while it iterates over it.
This invalidates the iterator.
Retrieve the updated iterator returned from the erase() function.
More details here: iterate vector, remove certain items as I go
Or, as you seem to delete just one contact at a time, just break your for loop after the first call to erase.
I am writing a code about input strings, then compare them with other elements in the vector and, if there's a positive match, don't put them into. I wrote this:
// NamePair.cpp : definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include "std_lib_facilities.h"
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
vector<string> names;
vector<int> scores;
string name = "0";
int score = 0;
int error = 0;
int n = 0;
cout << "Type a name and a score: " << endl;
while (cin >> name >> score) {
++n;
cout << "This is # " << n << " name you typed." << endl;
if (n >= 2) {
for (int i : scores) {
if (names[i] == name) {
cout << "You have already typed this name dude!" << endl;
}
else if (name != "NoName") {
names.push_back(name);
scores.push_back(score);
}
else {
break;
}
}
}
}
for (int i = 0; i < scores.size(); ++i) {
cout << names[i] << "\t" << scores[i] << endl;
}
keep_window_open();
return 0;
}
The issue is that when I am trying to run the program it works but it seems to be stuck at a point where I continuously add names and scores but it doesn't do anything apparently (neither shows a warning message nor stops if "NoName" string is typed). I can't figure out why! I have tried to re-write it all but with the same result...
Thanks for help!
Your checking whether name exists in vector is wrong. Change
if (names[i] == name) {
to
if ((std::find(names.begin(), names.end(), name) != names.end()) {
Also, it looks like the for (int i : scores) loop is unnecessary here.
An std::map would be best suitable here. This code snippet will help you
#include <bits/stdc++.h>
using namespace std;
int main() {
map<string, int> data;
string name;
int score;
for (int n = 0; cin >> name >> score; ++n) {
if (name != "NoName" || !data.count(name))
data[name] = score;
}
for (auto & i : data)
cout << i.first << " " << i.second << endl;
return 0;
}
See http://ideone.com/j3Gkiw
Your issue is in your for loop.
You try to push new elements into your vector inside the loop that iterates the vector. The vector starts out empty, so the program will never enter the loop and you will never actually push any elements into the vectors.