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.
Related
I'm trying to make a program that prints all the numbers from 100-999. After that you get to choose how many numbers you want to find. Then you type the number's position and it will be outputed.
There is one problem. The string, named str, stops storing at the number 954.
Here's the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//Prints to myFile the numbers from 100 to 999 without a space in between. Like this: 100101102...999
ofstream myFile("numere.txt");
for(int i = 100; i <= 999; i++)
myFile << i;
//Makes the string str to store the line: 100101102103...999. But only stores until 954 (100101102..954)
ifstream myFileRead("numere.txt");
string str;
while(getline(myFileRead, str))
cout << str << endl;
//Ouputs the lenght that should be 2700 but is instead 2565
cout << endl;
cout << "String legth: " << str.size() << endl;
cout << endl;
int n, k;
cout << "Enter how many numbers do you want to find: ";
cin >> n;
for(int i = 1; i <= n; i++){
cout << "Enter number position(it starts from 0) : ";
cin >> k;
cout << "Here's the number on position " << k << ": " << str.at(k);
cout << endl;
}
system("pause>0");
}
Thanks for your attention. I’m looking forward to your reply.
C++ streams are buffered. When you use << to write to a file it is not immediately written to the file.
Try to close or flush the ofstream before you read from it:
myFile.close(); // or...
myFile.flush();
For more details I refer you to flush() and close().
PS: Actually it is rather rare that you need to close a fstream explicitly. You wouldn't need to do it when you used seperate functions for writing and reading:
void write_to_file() {
std::ofstream myFile("numere.txt");
//...
}
void read_from_file() {
std::istream myFile("numere.txt");
//...
}
Because the destructor of ofstream already closes the file.
forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}
I am getting this error every time I try to run my program.
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of
'std::logic_error' what(): basic_string::_M_construct null not valid
#include <iostream>
#include <string>
using namespace std;
struct Bin
{
string desc;
int partsQty;
};
void addParts(Bin bList[], int i);
void removeParts(Bin bList[], int i);
int main() {
char response;
int binNumber;
const int NUM_OF_BINS = 11;
Bin binList[NUM_OF_BINS] = {
{0,0},
{"Valve", 10},
{"Earing",5},
{"Bushing",15},
{"Coupling",21},
{"Flange",7},
{"Gear",5},
{"Gear Housing",5},
{"Vaccum Gripper",25},
{"Cable",18},
{"Rod",12}
};
for(int i=1;i < 11;i++)
{
cout << "Bin #" << i << " Part: " << binList[i].desc << " Quantity " << binList[i].partsQty << endl;
}
cout << "Please select a bin or enter 0 to terminate";
cin >> binNumber;
cout << "Would you like to add or remove parts from a certain bin?(A or R)";
cin >> response;
if(response == 'a')
addParts(binList, binNumber);
else if(response == 'r')
removeParts(binList, binNumber);
return 0;
}
void addParts(Bin bList[], int i)
{
int parts;
int num;
cout << "How many parts would you like to add?";
cin >> num;
parts = bList[i].partsQty + num;
cout << "Bin # " << i << " now contains " << parts << " parts";
}
void removeParts(Bin bList[], int i)
{
int parts;
int number;
cout << "Which bin would you like to remove parts to?";
cin >> i;
cout << "How many parts would you like to remove?" << endl;
cin >> number;
parts = bList[i].partsQty - number;
if(parts < 0)
cout << "Please enter a number that isn't going to make the amount of parts in the bin negative.";
cin >> number;
parts = bList[i].partsQty - number;
cout << "The remaining amount of parts in bin #" << i << " is " << parts;
}
It comes from:
{0,0}
in your list of initializers for binList. 0 is not a correct initializer for std::string. You could perhaps use {"", 0} instead, or even {}.
Another idea might be to revise your program logic so that you do not require a dummy entry at the start of the array.
There is my friend's code. It works, but we would like to ask our user how many times he wants to type informations. Simplier, We don't know how to ask my user for N ("const int N = 3" line). We've tried changing "const int" into "int", but then an error shows up "expression must have a constant value".
#include <iostream>
using namespace std;
struct T_dane_ksiazki
{
char imie[15];
char nazwisko[30];
char tytul[45];
int rokwydania;
int nrwydania;
};
void WCZYTAJ_dane(T_dane_ksiazki& dane) /*wczytanie informacji o książce*/
{
cout << "\nimie autora: ";
cin >> dane.imie;
cout << "nazwisko autora: ";
cin >> dane.nazwisko;
cout << "tytul ksiazki: ";
cin >> dane.tytul;
cout << "rok wydania: ";
cin >> dane.rokwydania;
cout << "numer wydania: ";
cin >> dane.nrwydania;
}
void WYSWIETL_dane(T_dane_ksiazki dane) /*wczytanie informacji o książce*/
{
cout << "\nimie autora: " << dane.imie;
cout << "\nnazwisko autora: " << dane.nazwisko;
cout << "\ntytul ksiazki: " << dane.tytul;
cout << "\nrok wydania: " << dane.rokwydania;
cout << "\nnumer wydania: " << dane.nrwydania << "\n";
}
const int N = 3;
int Zapytajka()
{
cout << N<< "\n";
return 1;
}
int main()
{
T_dane_ksiazki daneq[N];
Zapytajka();
cout << "Podaj informacje o ksiazkach: \n";
for (int i = 0; i<N; i++)
{
WCZYTAJ_dane(daneq[i]);
}
cout << "\n\nInformacje o ksiazkch: \n";
for (int i = 0; i<N; i++)
{
WYSWIETL_dane(daneq[i]);
}
cout << "\nKoniec programu. Nacisnij ENTER";
cin.ignore(); cin.get();
return 1;
}
C++ only supports arrays whose size is constant. However, if you want a non-constant size, you can use vector, which was designed specifically for this purpose.
Example:
#include <vector>
...
int main()
{
Zapytajka();
cout << "Podaj informacje o ksiazkach: \n";
int n;
cin >> n;
std::vector<T_dane_ksiazki> daneq(N); // moved here and modified
for (int i = 0; i<N; i++)
{
WCZYTAJ_dane(daneq[i]);
}
...
}
I changed an array to a vector, and moved its definition to after the value of n is determined. I also changed N to n because it's no longer a constant, and it's a common convention to allocate lower-case names to variables.
Edit: I missed that it is a C++ question. The answer for C++ is that you should use a C++ container, probably a vector. These containers are the reason that the variable length arrays introduced in C in 1999 discussed below do not exist in C++: There is no real need for them. (There is a discussion whether to introduce something like it but it has non-trivial implications for the type system.)
You can have variable length arrays in C99 programs (for gcc: compile with "-std=c99"). That is, you can make N a non-const and the program should still compile and run properly (I didn't check every detail, but it looks pretty straightforward).
In pre-99 C you have to allocate dynamically with malloc or simply define an array which is big enough for the biggest conceivable number and use only part of it.
The program works all the way up until it checks for the name the user enters. When you enter the name you wish to search for in the array of structures that have been imported from a file full of customer info) it comes back segmentation fault core dumped. This puzzles me.
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
char name[50];
string email;
long int phone;
string address;
};
#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];
void readIn(ifstream& file){
int i=0;
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
}
void getAccount(){
char userPick[50];
char streamName[50];
cout << " What account will we be using? " << endl;
cin.getline(streamName, 50);
for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
}
}
}
int main(){
ifstream file;
file.open("2.dat"); //opens data account records text
readIn(file);
getAccount();
delete account;
return 0;
}
Your loop keeps reading everything into the initial element of the array:
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
because the value of i is never incremented. You can convert this to a for loop, like this:
for (count = 0 ; count < MAX && !file.eof() ; count++) {
file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}
Note that I changed i to count:
AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;
This will help you solve another problem - determining when the array ends in the getAccount function. Currently, you assume that the record is always there, so the outer loop keeps going on. Now that you have count, you could change the loop like this:
for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
break;
}
}
if (i == count) {
cout << "Not found." << endl;
}