C++ cout only prints sometimes - c++

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.

Related

How to get the correct amount of decimals using double in C++

Basically if I write 15.20 I want 15.20 to return and if I write without any extra zeros or any rounding so that the 0 is still printed out.
I tried using setprecision, but it just adds a bunch of zeros.
my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double flyttal;
cout << "Skriv in ett flyttal: ";
cin >> flyttal;
cout << "Du skrev in flyttalet: " << fixed << setprecision(2) << flyttal << endl;
return 0;
}
Now thats fine for the float value 15.20 but if I want to write 1.315456 I will only get 1.32. I want to be able to get the same amount of decimals as I put in.

How do i get a user to pick a number in c++

i am trying to make the user pick a number thats leads to a another code in c++ how do i do that?
cout << "Choose a text: "
getline(????)
1:
code number one
2.
text number 2
Pick a number?
I would assume you are talking about inputing a integer.
getline mostly is used for a string and spaces between each words, or a word.
For example if the input is like "Happy thanks giving"
the code would be like:
#include <iostream>
#include <string> //to use getline(cin, variable_name)
using namespace std;
int main()
{
string sentenceWithSpace;
cout << "get input" << endl;
getline(cin,sentenceWithSpace);
cout << sentenceWithSpace << endl;
system("pause"); // include this line if you use VS
return 0;
}
if the user is just inputing a value like 1,2,3,4,5,6
#include <iostream>
using namespace std;
int main()
{
int thisIsJustAInteger;
cout << "get input" << endl;
cin >> thisIsJustAInteger;
cout << thisIsJustAInteger << endl;
system("pause"); // include this line if you use VS
return 0;
}

C++ code runs forever and eats memory

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.

std::cin while loop gives a strange result

As of late, I've been doing a complete review of C++ and came across a code snippet containing the following:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a)
{
b+=a;
}
cout << b << endl;
return 0;
}
The code snippet seems very straightforward: it puts input from the console into a and adds this onto b, for as long as valid input is presented. However, whenever I try to run this program with an input of integers, seperated with spaces, it gives a very large negative integer (-1218019327 being the most recent result, when the entire input only consisted of the number '1'). Only when I modify the code does it give correct output:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a)
{
cout << a << endl;
b+=a;
}
cout << b << endl;
return 0;
}
Why does adding a cout statement change the result of my code so thouroughly (yet positively)?
Both programs result in undefined behavior, you did not initialize b. Try:
int b = 0;
You have to initialize b=0;. Or b will give you garbage value.
#include <iostream>
using namespace std;
int main()
{
int a, b=0;
while (cin >> a)
{
cout << a << endl;
b+=a;
}
cout << b << endl;
return 0;
}
By pressing ctrl-z you will get the value of b.

Testing for an integer in c++

I'm trying to write a c++ program that tests each input integer, and stops if the input is invalid.
Here is my code, without the testing part:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
cin >> i;
cout << endl << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
How can I test the input for validity?
The easiest is to use std::getline to read a whole line of input into a std::string, and then test whether that string is a valid integer specification.
It's also possible to do this by testing the failure state of cin, and clearing it, but that way lies an assortment of complications that you don't want.
In order to test the string you can use a high level std::istringstream (just read from it and test its failure state after) or, more efficient but a little more complicated, strtol from the C library (the latter is what a C++ stream uses internally).
You need to test whether a string is an integer without crashing.
You can do this with strtol(). It converts the string to an integer, and reports on the first character that is not a legal char for a number. No invalid characters means the entire string was an integer.
There is a good description and example of how to use it here:
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
while(!(cin >> i))
{
cin.clear();
cin.ignore();
cout << "\nInput was invalid, please re-enter: ";
}
cout << endl << "The integer is: " << i << endl;
} while(i != 0);
system("Pause");
return 0;
}