I have to make a program for a class that displays one star for every three degrees for each temperature read from an input file. I think I did ok, the code compiles. However, when I actually run it, I have a few problems:
1) when I run it without pressing ctrl+f5 in codelite it exits immediately, even though I have 'return 0;' at the end.
2) the console only shows stars for maybe half of the numbers, the rest are blank.
3) the numbers aren't lining up although I have set them all to the same width in my loop.
Here's what I see when I use ctrl+f5: http://imgur.com/w6jqPp5
Here's my code:
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
//declare variables for input/loops
string graphLine = " | ";
int tempCount = 0;
int tempStars;
int tempValue;
int printedStars;
//Title
cout << "Welcome to the Hourly Temperature Bar-Graph Maker 1.0!" << endl;
//read input file, name it "tempData"
ifstream tempData;
tempData.open("temperatures.txt");
//display error if the input file read failed
if(!tempData) {
cout << "ERROR: The input file could not be read." << endl;
return 0;
}
cout << "Temperatures for 24 hours(each asterisk represents 3 degrees): " << endl;
//print the temperature range(horizontal label for graph)
cout << "-30 0 30 60 90 120" << endl;
//read a temperature, output the bar for each temperature
while (tempCount < 24) {
//read in temperature value
tempData >> tempValue;
//distinguish between negative and positive temperatures
if(tempValue >= 0) {
tempStars = tempValue/3;
cout << tempValue << setw(5) << graphLine;
//print the appropriate number of asterisks for the temperature
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << endl;
}
//print the stars before the line
else {
tempStars = tempValue/3;
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << tempValue << setw(5) << graphLine << endl;
}
tempCount++;
}
tempData.close();
return 0;
}
The program is just finishing normally - put a call to cin.getline or some other input call if you want it to wait. Alternatively run it through the debugger and put a breakpoint on the return 0 line.
You don't initialize or reset printedStars before you use it. Put printedStars = 0; before your star printing loops.
Move the setw(5) bit in the cout calls to before the value, so the value is output with a width of 5.
Related
I have a c++ program that is supposed to read data from a file into an array. Once the array is set up, the user inputs a row number they want displayed and the program is supposed to display the value stored in that row. The program successfully reads the data into the array but it doesn't display the value stored in the row, instead it displays the memory location. Here is the code I wrote:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream SeatPrices;
static const int NUM_ROWS = 15;
static const int NUM_SEATS = 30;
string SeatStructures[NUM_ROWS][NUM_SEATS];
double price[NUM_ROWS];
int rowRequested;
SeatPrices.open("SeatPrices.dat");
if (!SeatPrices)
cout << "Error opening SeatPrices data file.\n";
else
{
for (int rows = 0; rows < NUM_ROWS; rows++)
{
SeatPrices >> price[NUM_ROWS];
cout << endl << "Row " << (rows + 1) << ":\t";
cout << "$" << price[NUM_ROWS];
}
cout << endl << endl;
}
SeatPrices.close();
cout << "In which row would you like to find seats(1 - 15)? ";
cin >> rowRequested;
cout << fixed << showpoint << setprecision(2);
cout << "Price per seat: $" << price[rowRequested] << endl;
return 0;
}
It looks like you're reading all the data from the file into price[NUM_ROWS], which is one past the end of the array. Since you immediately cout this value, it'll look like the program is working. You probably want to read values into price[rows].
new to the forums here and beginning to learn C++. This site has already helped me so much with syntax and other things. What I'm trying to do with my code is have the number print to screen, have the time delay, then print the next number. Currently the time delay works, but it prints all 13 numbers generated. Any ideas of what I'm doing wrong?
Here's my code:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <windows.h>
using namespace std;
int main( )
{
// Function prototypes
int random ( int minValue, int maxValue);
// Constant declarations
const int maxValue = 9;
const int minValue = 0;
// Local variable declarations
int seed;
int numberOfPeople;
int peopleCount = 0;
int numberCount;
int number;
// Initialize the random number generator
cout << "Welcome to the Lottery!" << endl;
cout << "Enter your lucky number to start: " << endl;
cin >> seed;
srand (seed);
// Generate and display numbers
cout << "Enter the number of people participating in the lottery:" << endl;
cin >> numberOfPeople;
cout << "Your lucky lottery numbers for the day are:" << endl;
cout.setf (ios::left, ios::adjustfield);
cout << setw(8) << "Pick 3" << setw(10) << "Pick 4" <<
setw(15) << "Pick 6" << endl;
while (peopleCount < numberOfPeople) {
numberCount = 0;
while (numberCount < 13){
number = random (minValue, maxValue);
Sleep (500); // pauses for half a second
cout << number << " ";
if (numberCount == 2){
cout << " "; }
else if (numberCount == 6){
cout << " "; }
else if (numberCount == 12){
cout << endl; } //end if, else if
numberCount++;
} //end nested while
peopleCount++;
} // end while
return 0;
} // end main()
/**
* Produces a pseudo-random number
* #param minValue minimum value that can be generated
* #param maxValue maximum value that can be generated
*
* #return psuedo-random number in the specified range
*/
int random ( int minValue, // min possible number to be generated
int maxValue) // max possible number to be generated
{
return ( (rand() % maxValue) + minValue);
} // end random()
cout is generally buffered, and the newline causes the buffer to be flushed to the screen. As you display the numbers on the same line, this could explain that everything is displayed at onece despite the delay that you've build in.
Use cout.flush(); to force output to be done without buffering delay. You could as well use the manipulator form: cout << number << " " << flush;
Here is the deal guys:
I'm making a stat generator. The program has a menu(not fully developed in this program, but I have previous code that will work)It asks for a name and then stores it to Character1.
Then it prompts that it is generating your scores.The function GenerateScore() takes 3 random numbers with the range 1-6 each, adds them together and returns the sum.
I want this to loop 6 times and store total into the array Stats[6].
Then I am sending the Character1 and the array to the txt file called charactersave.txt.
It saves whatever name I input each time but I get this when I open the txt file. I get this
anthony-858993460-858993460-858993460-858993460-858993460-858993460-858993460-117763858413957408144036511139574241439271911568132815670376-1177638760
Any help on this would be greatly appreciated,
#include <iostream>
#include <cstring>
#include <array>
#include <string>
#include <fstream>
using namespace std;
int GenerateScore();
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
do
{
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
GenerateScore()>> Stats[i];
}
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; Stats[i]; i++)
{
savecharinfo << Stats[i]; //writing numbers of values2 in the file
}
}
else cout << "File could not be opened." << endl;
break;// this is unfinished after this point
}
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program if c or C is entered.
system("PAUSE");
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}
>> can only be used for std::ostream to achieve streaming behavior.
Change
GenerateScore()>> Stats[i];
to
Stats[i] = GenerateScore();
I need to create a program that takes integers from a text file, and outputs them, including the number, lowest number, largest number, average, total, N amount of numbers, etc. I can do this just fine with the code below, but I also need to process the text per line. My sample file has 7 numbers delimited with tabs per row, with a total of 8 rows, but I am to assume that I do not know how many numbers per row, rows per file, etc. there are.
Also, for what it's worth, even though I know how to use vectors and arrays, the particular class that I'm in has not gotten to them, so I'd rather not use them.
Thanks.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int num;
int count = 0;
int total = 0;
int average = 0;
string str = "";
int numLines = 0;
int lowNum = 1000000;
int highNum = -1000000;
ifstream fileIn;
fileIn.open("File2.txt");
if (!fileIn) {
cout << "nError opening file...Closing program.n";
fileIn.close();
}
else {
while (!fileIn.eof()) {
fileIn >> num;
cout << num << " ";
total += num;
count++;
if (num < lowNum) {
lowNum = num;
}
if (num > highNum) {
highNum = num;
}
}
average = total / count;
cout << "nnTotal is " << total << "." << endl;
cout << "Total amount of numbers is " << count << "." << endl;
cout << "Average is " << average << "." << endl;
cout << "Lowest number is " << lowNum << endl;
cout << "Highest number is " << highNum << endl;
fileIn.close();
return 0;
}
}
One way to deal with the individual lines is to skip leading whitespaces before reading each value and to set the stream into fail-state when a newline is reached. When the stream is good after skipping and reading a value, clearly, there was no newline. If there was a newline, deal with whatever needs to happen at the end of a line, reset the stream (if the failure wasn't due to reaching eof()) and carry on. For example, the code for a loop processing integers and keeping track of the current line could like this:
int line(1);
while (in) {
for (int value; in >> skip >> value; ) {
std::cout << "line=" << line << " value=" << value << '\n';
}
++line;
if (!in.eof()) {
in.clear();
}
}
This code uses the custom manipulator skip() which could be implemented like this:
std::istream& skip(std::istream& in) {
while (std::isspace(in.peek())) {
if (in.get() == '\n') {
in.setstate(std::ios_base::failbit);
}
}
return in;
}
I have got an input file with following data
2
100
2
10 90
150
3
70 10 80
Now, I am able to read till 4th line ( 10 90) but when reading 5th line(150), the file pointer seems to be stuck at 4th line. I have tried infile.clear() just incase. How do I make sure that file pointer is moving correctly or position it at next line? Appreciate your feedback.
-Amit
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(void) {
int cases;
int total_credit=0;
int list_size=0;
string list_price;
//Read file "filename".
ifstream infile;
infile.open("A-large-practice.in",ifstream::in);
if(!infile.is_open()) {
cout << "\n The file cannot be opened" << endl;
return 1;
}
else {
cout<<"Reading from the file"<<endl;
infile >> cases;
cout << "Total Cases = " << cases << endl;
int j=0;
while (infile.good() && j < cases) {
total_credit=0;
list_size=0;
infile >> total_credit;
infile >> list_size;
cout << "Total Credit = " << total_credit << endl;
cout << "List Size = " << list_size << endl;
//cout << "Sum of total_credit and list_size" << sum_test << endl;
int array[list_size];
int i =0;
while(i < list_size) {
istringstream stream1;
string s;
getline(infile,s,' ');
stream1.str(s);
stream1 >> array[i];
//cout << "Here's what in file = " << s <<endl;
//array[i]=s;
i++;
}
cout << "List Price = " << array[0] << " Next = " << array[1] << endl;
int sum = array[0] + array[1];
cout << "Sum Total = " << sum << endl;
cout <<"Testing" << endl;
j++;
}
}
return 0;
}
The problem is that you're using ' ' (space) as your "line terminator" for getline. So when you're reading the numbers on line 4 into the string s, the first one will be "10" and the second will be "90\n150\n3\n70" -- that is, everything up to the next space. This is almost certinaly not what you want and is leading to your confusion about where you are in the file. The next number you read will be 10, leading you to think you're on line 4 when in fact you're on line 7.
edit
The easiest way to fix this is probably to not use getline at all and just read ints directly from the input:
while (i < list_size)
infile >> array[i++];
This ignores the newlines altogether, so the input might as well be all on one line or split between lines randomly, but as you have an initial number that tells you how many numbers to read, that's just fine.