I keep gettin this error on my code. My program was running perfectly just a few minutes ago and all of a sudden it kept throwing this error at me. I tried to find the error by using cout << "here" << endl in between some lines and sometimes it usually stops within my for loop inside the readInName() functions. Sometimes it would fully run and print out everything even the "here". Other times i would just get the same error.
#include <fstream>
#include <string>
using namespace std;
// global variables
// these must be changed depending on the file.
const int SIZE = 10; // num of students
const int AMOUNTOFGRADES = 5; // num of tests per student
ifstream input;
// function declarations
void readInName();
float calculateAvgAndGrade(int count);
void header();
int readInGrades(int);
int main(){
header();
readInName();
return 0;
}
void readInName(){
string name[SIZE] = {""};
input.open("grade.txt");
int row,column;
int count;
for(row = 0; row < SIZE; row++){
input >> name[row];
cout << setw(10) << name[row] << ": ";
count = readInGrades(row);
cout << setw(5) << calculateAvgAndGrade(count) << endl;
}
input.close();
}
int readInGrades(int){
int r,c;
int grades[SIZE][AMOUNTOFGRADES] = {0};
int count = 0;
for(c = 0; c < AMOUNTOFGRADES; c++){
input >> grades[r][c];
cout << setw(5) << grades[r][c] << " ";
count = count + grades[r][c];
}
return count;
}
float calculateAvgAndGrade(int count){
return float(count)/AMOUNTOFGRADES;
}
void header(){
cout << setw(15) << " Names " << setw(20) << "Grades " << setw(18) << "Avg " << endl;
cout << setfill('-') << setw(53) << '-' << endl << setfill(' ');
}
In readInGrades(), r is used uninitialized as an index to write into grades[r][c], which is undefined behavior. So r may by chance have any value and write to arbitrary locations in memory. This would sometimes corrupt the stack and trigger a segmentation fault. A helpful tool to troubleshoot these kinds of errors is AddressSanitizer, enabled in clang or gcc by compiling with -fsanitize=address, or if you are using Xcode, there is an option for it. Another great tool is valgrind.
In my opinion:
input >> grades[r][c];
r - isn't initialized.
Related
I try this code using a method, array, and struct, but it doesn't produce output at all.
I also use most types of include, but it still doesn't produce any output.
#include<conio.h>
#include<iostream>
#include<stream>
#include<string>
#include<stream>
using namespace std;
struct PetLabel {
string petname;
string pettype;
int petprice;
string petowner;
string phoneno;
};
PetLabel pet [10];
stringstream ss;
void DataPet();
void petPrice();
void findOwner();
int main(){
DataPet();
findOwner();
petPrice();
return 0;
}
void DataPet(){
ifstream infile;
infile.open("petSold.txt");
string cnvt[10];
for(int i = 0; i < 10; i++){
getline(infile, pet[i].petname, ',');
getline(infile, pet[i].pettype, ',');
getline(infile, cnvt[i], ',');
ss << cnvt[i];
ss >> pet[i].petprice;
getline(infile, pet[i].petowner, ',');
getline(infile, pet[i].phoneno);
ss.clear();
}
infile.close();
}
void findOwner(){
int chosen;
for (int i = 0; i < 10; i++){
if (pet[i].petname == "Uyasolu"){
i = chosen;
}
}
cout << "Owner name : " << pet[chosen].petowner << " Phone no : " << pet[chosen].phoneno << endl;
}
void petPrice(){
ofstream outfile("catSold.txt");
outfile << "The cat sold with price greater than RM1000" << endl;
for (int i = 0; i < 10; i++){
if (pet[i].petprice > 1000){
cout << pet[i].petname << "," << pet[i].pettype << "," << pet[i].petprice << "," << pet[i].petowner << "," << pet[i].phoneno << endl;
}
}
outfile.close();
}
the output that I get is:
Owner name : Phone no :
but I can't understand, because there is no syntax error at all.
Is there anything I can add, so I can get the right output?
This method is weird:
void findOwner(){
int chosen;
for (int i=0;i<10;i++){
if (pet[i].petname == "Uyasolu"){
i = chosen;
}
}
cout<<"Owner name : "<<pet[chosen].petowner<<" Phone no : "<<pet[chosen].phoneno<<endl;
}
I think you mean chosen = i instead.
findOwner() is coded wrong.
int chosen; is uninitialized before the loop is entered. Inside the loop, chosen is never updated (i is updated instead, which affects the looping). After the loop is done, chosen has an indeterminate value, so accessing pet[chosen] is undefined behavior.
It should look more like this instead:
void findOwner(){
int chosen = -1;
for (int i = 0; i < 10; i++){
if (pet[i].petname == "Uyasolu"){
chosen = i;
break;
}
}
if (chosen != -1)
cout << "Owner name : " << pet[chosen].petowner << " Phone no : " << pet[chosen].phoneno << endl;
else
cout << "Pet not found" << endl;
}
Alternatively:
void findOwner(){
for (int i = 0; i < 10; i++){
if (pet[i].petname == "Uyasolu"){
cout << "Owner name : " << pet[i].petowner << " Phone no : " << pet[i].phoneno << endl;
return;
}
}
cout << "Pet not found" << endl;
}
There are some other issues in your code, too:
don't use <conio.h>, its old, and you are not using anything from it anyway.
you have #include<stream> twice, and also <stream> should be <sstream>
string cnvt[10]; should be string cnvt; and then cnvt[i] should be cnvt. You don't need a whole array when you are converting only 1 string at a time.
ss.clear(); does not do what you think it does. You need to use ss.str("") instead. Or, simply move the declaration of ss inside the loop as a local variable so it is destroyed and recreated on each loop iteration.
petPrice() is creating an output catSold.txt file, but is not writing anything to it.
I want to store the elements of struct into a text file. I have multiple inputs and this is what I have done, however, I can only store the latest inputs but not all the input. Thanks in advance for the help! Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
struct ProcessRecords {
string ID;
int arrival;
int wait;
int burst;
void putToFile() {
ofstream input;
input.open ("process.txt");
input << ID << "\t" << arrival << "\t" << wait << "\t" << burst << endl;
input.close();
}
};
int main() {
int numProcess;
int algo;
cout << "\n\t\t=== CPU SCHEDULING ALGORITHMS ===\n";
cout << "\n\t\tEnter number of processes: ";
cin >> numProcess;
ProcessRecords process[numProcess];
string processID[numProcess];
int arrTime[numProcess];
int waitTime[numProcess];
int burstTime[numProcess];
cout << endl << endl;
for (int i = 0; i < numProcess; i++) {
cout << "\n\tEnter process ID for Process " << i+1 << ":\t ";
cin >> processID[i];
process[i].ID = processID[i];
cout << "\n\t\tEnter arrival time for " << processID[i] << ":\t ";
cin >> arrTime[i];
process[i].arrival = arrTime[i];
cout << "\n\t\tEnter waiting time for " << processID[i] << ":\t ";
cin >> waitTime[i];
process[i].wait = waitTime[i];
cout << "\n\t\tEnter burst time for " << processID[i] << ":\t ";
cin >> burstTime[i];
process[i].burst = burstTime[i];
process[i].putToFile();
}
return 0;
}
Here is my sample output:
First In C++(by C++ i mean standard C++ and not extensions), the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following statement is incorrect in your code :
int arrTime[numProcess]; //incorrect because size of array must be fixed and decide at compile time
Second you should append to the text file instead of overwriting it. For opening the file in append mode you can use:
input.open("process.txt", ofstream::app);
You can check here that the program works(append) as you desire, using input.open("process.txt", ofstream::app); . Also do note what i said about the size of array being compile time constant. I have not changed it in the link i have given. You can use std::vector for variable size container.
Hello I am making this question because on the for loop "for (grade = 0; grade != -1; numbOfTests++)" or in the getGrade function there seems to be an error if you enter the integer "-1" in the cin input first. More so it gives the "timeout: the monitored command dumped core" error. What is causing this? I looked up on google but the errors dont seem to be the same as mine. Id appreciate the help, my code is below.
#include <iostream>
const int EXTRA_CREDIT = 3;
void displayIntro();
int getGrade();
int finalAverage(int, int);
int main()
{
int grade, sum, numbOfTests, average;
displayIntro();
numbOfTests = -1;
sum = 0;
for (grade = 0; grade != -1; numbOfTests++)
{
grade = getGrade();
sum = sum + grade;
}
sum++;
average = finalAverage(sum, numbOfTests);
std::cout << "Exam average, including extra credit, "
<< "is: " << average << std::endl;
return 0;
}
void displayIntro()
{
std::cout << "This program will calculate the average(%) of "
<< "exam grades." << std::endl;
std::cout << "It will also add extra credit points to the exam "
<< "average given the course difficulty." << std::endl;
std::cout << "Enter all of the grades for one student. Type (-1)"
<< " when finished with that student." << std::endl;
std::cout << "If you have additional students, you will be prompted"
<< " to repeat the program at the end." << std::endl;
}
int getGrade()
{
int userGrade = 0;
std::cout << "Enter an exam grade (type -1 to quit):" << std::endl;
std::cin >> userGrade;
return userGrade;
}
int finalAverage(int runningSum, int counter)
{
int final;
final = (runningSum / counter) + EXTRA_CREDIT;
return final;
}
When -1 is the first input, numbOfTests++ in the for loop is executed once.
This causes numbOfTests to be zero and the finalAverage function will perform division by zero according to that. This may lead to runtime error.
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].
I am trying to make this code "move" from the left to right. I've been successful in moving it from to right. The problem is now, how do I run this infinitely? Okay I'm not familiar with C++ cause I'm a beginner. I tried to search the internet on how to make a code run infinitely, and I found a for(;;) loop, and I put it above where my first for loop will start. But it doesn't work. Can you give me tips or any hints?
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>
#include <windows.h>
using namespace std;
int main ()
{
string a;
cout <<"Enter String : ";
cin >> a;
cout << '\n' << '\n' << '\n' << '\n';
for(int x = 0; x <= 20; x++ ) {
Sleep(200);
system("cls");
cout <<"Enter String : ";
cout << a;
cout << '\n' << '\n' << '\n' << '\n';
cout << setw(x)<< a;
}
for(int y = 20; y <= 20; y-- ) {
Sleep(200);
system("cls");
cout <<"Enter String : ";
cout << a;
cout << '\n' << '\n' << '\n' << '\n';
cout << setw(y)<<a;
}
return 0;
}
The output should display like:
Enter string: Hello Friend
"Hello Friend" > it will move to the right and after 20 spaces.
< now it move back to the left < "Hello Friend"
And also I saw a "Void" code what does it do? and is it relevant to my code?
main culprit is this line for(int y = 20; y <= 20; y-- ) edit it to for(int y = 20; y >= 0; y-- ) then put both for loop inside while(1){ }
here's the complete code:
int main ()
{
string a;
cout <<"Enter String : ";
cin >> a;
cout << '\n' << '\n' << '\n' << '\n';
while(1){ //infinite loop starts
for(int x = 0; x <= 20; x++ ){
Sleep(200);
system("cls");
cout <<"Enter String : ";
cout << a;
cout << '\n' << '\n' << '\n' << '\n';
cout << setw(x)<< a;
}
for(int y = 20; y >= 0; y-- ){ //make sure this condition
Sleep(200);
system("cls");
cout <<"Enter String : ";
cout << a;
cout << '\n' << '\n' << '\n' << '\n';
cout << setw(y)<<a;
}
}
return 0;
}
"And also I saw a "Void" code what does it do? and is it relevant to my code?": Basically it means "nothing" or "no type".
There are 3 basic ways that void is used:
Function argument: int func(void) -- the function takes nothing.same as int func()
Function return value: void func(int) -- the function returns nothing
Generic data pointer: void* data -- 'data' is a pointer to data of unknown type, and cannot be dereferenced.
and NO it is NOT relevant to your code.
Generally you can write an infinite loop like this:
while (1){
//do coding
}
While loops run while the statement inside () is true. 1 is always true.
You can use "break;" to stop an infinite loop whenever you wish to do so.