How to save the data in different files using for loop? - c++

In the following code for loop returns me 5 values [0,1,2,3,4]. I want to get 5 text files with the name h_0.0, h_1.0, h_2.0, h_3.0, h_4.0 and h_0.0 should store first number of for loop i.e.,0 file h_1.0 should store second number of for loop i.e., 1 and so on.
#include <iostream>
using namespace std;
int *name()
{
static int n[5];
for (int i = 0; i < 5; i++)
{
n[i] = i;
}
return n;
}
int main()
{
int *p;
p = name();
for (int i = 0; i < 5; i++)
{
cout << *(p + i) << endl;
}
return 0;
}

If I understand well what you want to do, here is some basic solution, for demo,
creating files in current folder:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int* name() {
static int n[5];
for (int i = 0; i < 5; i++) {
n[i] = i;
}
return n;
}
int main() {
int* p;
p = name();
for (int i = 0; i < 5; i++)
{
int fn = *(p + i);
std::stringstream ss;
ss << fn;
std::string fname = "h_" + ss.str();
fname += ".0";
std::ofstream f(fname.c_str());
if (f.good()) {
f << fn;
cout << "file h_" << fn << ".0 created" << endl;
}
}
return 0;
}

Use filestream.
#include <fstream> // include filestream
#include <sstream> // for storing anything that can go into a stream
#include <string>
int main()
{
std::string nameholder;
std::ofstream outputstream;
for (int i = 0; i < 5; i++)
{
nameholder = "h_"; // reset name every loop
std::stringstream sstreamholder; // remake stringstream every loop
sstreamholder << i; // store current number in stringstream
nameholder += sstreamholder.str() + ".0"; // append what sstreamholder currenlty has and the file extension .0
outputstream.open(nameholder); // write the filename with the updated name
outputstream << i << std::endl; // write the number in the file
outputstream.close(); // close the file so it's ready for the next open
}
return 0;
}

Related

How to convert a string into a char matrix

I want to put a string into a char nxn matrix, which makes the string "abcdefghi" into a 3x3 char matrix, and become
{abc;def;ghi}
but it does not save right.
I try to output every i, j,ch[i][j] and s[j+i*3] in the first loop, and they look right, but in the final output, it goes wrong.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
char ch[2][2];
string s = "abcdefghi";
int i, j;
for (i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
ch[i][j] = s[j + i * 3];
}
}
for (i = 0; i < 3; i++)
{
cout << ch[i] << endl;
}
return 0;
}
I want the ch matrix become
{abc;def;ghi}
but the output is
{abdegi;degi;gi}
Your code has two problems:
1. char ch[2][2]; is supposed to be char ch[3][3];
2. You assume you can print an entire row with a single cout << ch[i] << endl;, but the rows don't end with a '\0', thus cout prints everything until it hits a null.
Here's a fixed version:
#include <iostream>
int main()
{
char ch[3][3];
auto s = "abcdefghi";
auto* ptr = s;
for (auto& r1 : ch)
{
for (auto& r2 : r1)
{
r2 = *ptr++;
}
}
for (const auto& r1 : ch)
{
for (auto r2 : r1) // char is trivial to copy
{
std::cout << r2;
}
std::cout << '\n';
}
std::cout << std::flush;
return 0;
}

Having issues eliminating duplicates and sorting from C++ array outfile

Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max

Displaying 2 iterated arrays in one for loop

I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .

write to txt file in c++

I want to write random sorted data to a file. I'm using g++, but after running the program there was no data saved to the file.
This is the code:
#include <string>
// basic file operations
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int ra;
int pp = 0;
ofstream myfile("fi21.txt");
myfile.open("fi21.txt");
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
ra = (rand()) + pp;
pp = ra;
std::string vv;
vv = "1,";
vv += i;
vv += ",";
vv += ra;
vv += "\n";
// myfile << vv;
myfile.write(vv.c_str(), sizeof(vv));
}
}
// myfile.close();
return 0;
}
Your code should/could look like this:
#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int ra;
int pp = 0;
ofstream myfile("fi21.txt"); // This already opens the file, no need to call open
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
ra = rand() + pp;
pp = ra;
// This will concatenate the strings and integers.
// std::string::operator+= on the other hand, will convert
// integers to chars. Is that what you want?
myfile << "1," << i << "," << ra << "\n";
}
}
return 0;
}
That superfluous call was the major problem, but also note that your attempt:
myfile.write(vv.c_str(), sizeof(vv));
has a mistake - sizeof(vv) is the number of bytes std::string takes on the stack, not how long it is. std::string::length or std::string::size is for that. Why to use the above at all, when you can myfile << vv;? I actually didn't even use std::string in the above code.

inserting vector element in queue

#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
struct process
{
int burst;
int ar;
};
int x = 4;
int arival[x];
int burst[x];
ifstream arrival, burrst;
arrival.open("arrival.txt");
burrst.open("burrst.txt");
for (int i = 0; i<x; i++)
{
arrival >> arival[i];
burrst >> burst[i];
}
arrival.close();
burrst.close();
vector<process> a[x];
for (int i = 0; i<x; i++)
{
a[i].push_back({ burst[i], arival[i] });
}
cout << "Process\t" << "Arrival Time\t" << "Burst Time\n";
for (int i = 0; i<x; i++)
{
char k = 'A';
cout << k << "\t" << a[i].back().burst << "\t" << a[i].back().ar << endl;
}
queue<process> wait, ready; /* Declare a queue */
wait.push(a[1]);
return 0;
}
The compiler is not allowing me to push vector value into queue When I try to insert a[1] in wait queue like this:
wait.push(a[1]);
I get the following error
invalid arguments
Please have a look and help me to remove the error.
I think what you are looking for is just a vector of process, not an array of vector of process
Instead of:
vector<process> a[x];
Use:
vector<process> a;
and then, in the for loop, use:
// a[i].push_back({ burst[i], arival[i] });
// ^^^ drop this.
a.push_back({ burst[i], arival[i] });