It seems to be in MakeData function, as that is what breaks the execution. I am very unsure as to why this is not working, as my instructor and many of my classmates have almost identical execution and it is fine. I know for a fact that an almost identical version of this code, with windows file name, also does not run on windows. I have compiled the code. I have run debuggers. Nothing turns up. The debuggers I have run have just run the code until either very obscure errors turn up or it essentially indicates that the process is in some kind of an infinite loop. Any help would be appreciated!
/*
*Program Description:A program to sort a series of strings and scores from a file.
*
*Programmer:Timothy A. Gass
*Date:01/17/17
*/
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
#include <vector>
#include <ctime>
using namespace std;
void makeData(string);
void getData(vector<string> &, vector<int> &, string);
int main(){
srand(time(0));
string fname = "/home/tim/dev/c++/chpt9/data.txt";
vector<string> name;
vector<int> score;
makeData(fname);
getData(name, score, fname);
for(int i = 0; i < score.size(); i++){
cout << score[i] << endl;
cout << name[i] << endl;
}
cout << "Press enter to exit." << endl;
cin.ignore();
cin.get();
return 0;
}
void makeData(string fname){
int rand1, rand2, rand3;
const int SCORE_MAX_SIZE = 100;
ofstream make(fname);
const int PEOPLE_NUM = 50;
vector<string> firstNames = {
"Gus",
"Taneka",
"Shane",
"Rosella",
"Bennett",
"Filiberto",
"Khadijah",
"Mafalda",
"Rusty",
"Janiece",
"Shavonne",
"Azalee",
"Enedina",
"Heidy",
"Lavelle",
"Darleen",
"Ashton",
"Glynis",
"Gale",
"Norene",
"Madaline",
"Elvin",
"Jacqueline",
"Kristofer",
"Zachary",
"Lorretta",
"Jim",
"Shanelle",
"Tonja",
"Alethia",
"Kasha",
"Katheleen",
"Joyce",
"Kirstin",
"Neil",
"Belkis",
"Maisha",
"Doretha",
"Eliseo",
"Rhiannon",
"Annamarie",
"Latoria",
"Jerica",
"Betsey",
"Delinda",
"Pamula",
"Porsha",
"Fredia",
"Wilda",
"Belen"
};
vector<string> lastNames = {
"Best",
"Shields",
"Finley",
"Blankenship",
"Hobbs",
"Nichols",
"Mcneil",
"Robles",
"Moyer",
"Hays",
"Elliott",
"Ruiz",
"Ritter",
"Gamble",
"Zamora",
"Cole",
"Larson",
"Ibarra",
"Choi",
"Santana",
"Gray",
"Crane",
"Campos",
"Wright",
"Morris",
"Flores",
"Newman",
"Santos",
"Li",
"Archer",
"Chavez",
"Avery",
"Mora",
"Liu",
"Lutz",
"Miles",
"Stewart",
"Austin",
"Wu",
"Turner",
"Brennan",
"Ferrell",
"Mcmillan",
"Whitney",
"Odonnell",
"Conley",
"Maxwell",
"Stafford",
"Carlson",
"Peck"
};
for(int i = 0; i < PEOPLE_NUM; i++){
rand1 = rand()%50;
rand2 = rand()%50;
rand3 = rand()%(SCORE_MAX_SIZE+1);
make << firstNames.at(rand1) + " " + lastNames.at(rand2) << endl;
make << rand3 << endl;
}
}
void getData(vector<string> &name, vector<int> &score, string fname){
ifstream get(fname);
string str;
int num;
if(get.fail()){
cout << "File could not be opened!" << endl;
}
else
{
while(!get.eof())
{
getline(get, str);
get >> num;
cin.ignore();
name.push_back(str);
score.push_back(num);
}
}
}
The comment made by Xin Huang was correct. It turns out the use of getline and cin resulted in some form of infinite loop that would eat memory, until the computer would eventually crash. I still have no idea why there is no solution to this, or why using cin and getline together could have such terrible consequences, especially considering there were really no error codes. Even still, replacing cin with getline in the getData function and then converting back to integer yields a clean program.
Related
I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Im new to coding in general and particularly to C++. Im trying to make something like google assistant, but text based, and am currently working on printing out the time when the user types in something like "timepls". I am using an arraybased kind of library for the code, so that I store preconfigured strings inside an array and compare the user input variable to each object in each array. and if the string matches with one of the arrays in the function, it gets executed. My problem is, that I have tried ctime and used the same initialisation code as with another function which I know works (its the only other function lol). Can someone help me to print out the current time with user input?
Heres my code:
#include <iostream>
#include <ctime>
using namespace std;
void howareyouq();
void whattimeisit();
int main(){
howareyouq();
whattimeisit();
}
void howareyouq(){
string howruq[4] = {"how are you?", "hru?", "how r u?", "hru"}; //array for the valid thingies
string user_input; //creating userinput variable
cin >> user_input; //writing user input to user_input
for (int i=0; i!=4; i++) {
if (user_input == howruq[i]) { //if the array contains something equal to user_input, this gets executed
cout << "Thanks, Im fine!" << endl; //the answer
}
}
}
void whattimeisit()
{
string thetimepls[] = {"timepls", "what time is it?", "how late is it?", "whats the time?", "time?"};
string user_input;
cin >> user_input;
for (int i=0; i++;) {
if (user_input == thetimepls[i]) {
time_t now = time(0);
char *date = ctime(& now);
cout << "The local date and time : " << date << endl;
}
}
}
Getting the bounds right and reading in a single time:
#include <iostream>
#include <ctime>
using namespace std;
void howareyouq(string const& user_input);
void whattimeisit(string const& user_input);
int main()
{
string user_input; //creating userinput variable
cin >> user_input; //writing user input to user_input
howareyouq(user_input);
whattimeisit(user_input);
}
void howareyouq(string const& user_input)
{
string howruq[4] = {"how are you?", "hru?", "how r u?", "hru"}; //array for the valid thingies
for (int i=0; i!=4; i++)
{
if (user_input == howruq[i]) { //if the array contains something equal to user_input, this gets executed
cout << "Thanks, Im fine!" << endl; //the answer
}
}
}
void whattimeisit(string const& user_input)
{
string thetimepls[] = {"timepls", "what time is it?", "how late is it?", "whats the time?", "time?"};
for (int i=0; i!=5; i++) {
if (user_input == thetimepls[i]) {
time_t now = time(0);
char *date = ctime(& now);
cout << "The local date and time : " << date << endl;
}
}
}
I need to figure out a bug with my program. When I type Hello World I am, it should count the number of spaces, but I keep getting 0 or 1. Below is my full program:
#include "windows.h"
#include <iostream>
#include <cctype>
using namespace std;
//Global declarations.
//Function prototypes.
void pause();
void numWords(string&);
int numWords(char []);
int main()
{
string userVal;
numWords(userVal);
char *conStr= new char[userVal.length()];
strcpy(conStr, userVal.c_str()); //String converted to a C-string.
int fin= numWords(conStr);
cout<< "The number of words in the sentence is "<< fin<< "."<< endl;
delete[] conStr;
conStr= 0;
pause();
return 0;
}
/***************************************FUNCTIONS**********************************************************************/
/*1st function to pause the program.*/
void pause()
{
cin.sync();
cin.ignore();
}
/*2nd function to ask the user for input. OP*/
void numWords(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
cin >> len;
}
/*3rd function to count the number of total spaces in the sentence.*/
int numWords(char usStr[])
{
int wrdCount= 0,
chrCount= 0,
index= 0;
while(usStr[index]!= '\0')
{
if(isspace(usStr[index]))
{
if(chrCount)
{
wrdCount++;
chrCount= 0;
}
}
else
chrCount++;
index++;
}
if(chrCount)
wrdCount++;
return wrdCount;
}
Can anyone please explain why it doesn't count the spaces, or if I need another loop mechanism to make this work? Thank you.
CoryKramer's suggestion was correct. cin will stop after the first whitespace. If you want to read a whole line, you use getline. I've made changes to your code to show this as well as renamed the function you use to get the sentence from the user. Also, you don't have to convert to a c-style string for this to work, a string works just fine.
//Function prototypes.
void pause();
void getSentence(string&);
int numWords(string&);
int main()
{
string userVal;
getSentence(userVal);
int fin = numWords(userVal);
cout << "The number of words in the sentence is " << fin << "." << endl;
pause();
return 0;
}
void getSentence(string &len)
{
cout << "Please enter a sentence and I will tell you how many words it has: " << endl;
getline(cin, len);
}
int numWords(string& usStr)
{
int wrdCount = 0,
chrCount = 0,
index = 0;
while(index < usStr.length())
{
...
}
if(chrCount)
wrdCount++;
return wrdCount;
}
You also probably want to #include <string>
When I run this program and input, for example, the number 7, the final cout command only works occasionally. Otherwise, the program exits successfully but the result is not printed. Why is this happening?
#include <iostream>
#include <cmath>
double treble(double);
int main()
{
using namespace std;
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
return 0;
}
double treble(double n)
{
return n * 3;
}
You should put using namespace std; outside of all function declarations, right under your #include directives. Also, when you say it's not printing, is it that the console is closing before displaying your result? In that case, I would advocate using a simple cin to "pause" the program. You can do it exactly as #Nihar says, though I might suggest using a string instead of an int so that it doesn't break if you accidentally type something other than an int.
Something like this:
#include <iostream>
#include <cmath>
using namespace std;
double treble(double);
int main(){
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
string foo;
cin >> foo;
return 0;
}
double treble(double n){
return n * 3;
}
try with this => put
int temp;
cin>>temp;
before return 0; to pause the program, because the execution finished (successfully) before the last output could be written to the console.
I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
return r;
}
int main()
{
int nr;
cout << "Give a number: ";
cin >> nr;
rev(nr);
cout << nr;
return 0;
}
The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
You need to change rev(nr); to nr = rev(nr);
or alternately change your function to:
void rev(int& x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
x = r;
}
You're doing it right, but you're not grabbing your return value (the reversed value).
To solve this, just assign or print the return value:
cout << rev(nr);
or
nr = rev(nr);
cout << nr;
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
There is a std::reverse function in the STL, which works with collections.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
long int i = 0;
do {
std::cout << "Gimme a number: " << std::endl;
} while (not (std::cin >> i)); // make sure it *is* a number
std::string display = std::to_string(i); // C++11
std::reverse(display.begin(), display.end());
std::cout << display << "\n";
}