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.
Related
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;
}
I need to pick m amount of random characters(letters) without repetition and im completely stuck, i keep getting only 1 random letter. How can i fix my code? Is there even a way to fix this or should i just scrap this idea and look for a solution from some kinf od tutorials?
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
bool repeat = false;
char letters[m];
char letter;
for(int i = 0; i < m; i++){
letter = rand()%26 +97;
repeat = true;
for(int j = 0; j < m; j++){
if(letters[m] == letters[j]){
repeat = false;
break;
}
}
if(repeat){
letters[m] = letter;
}
}
for (int i = 0; i < m; i++){
cout << letters[m];
}
}
You can use suffle -
#include <random>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
char charSet[]={'a','b','c'};//You can add all the charecters
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(charSet,charSet+3,g);
for(auto c : charSet)
{
std::cout<<c;
}
std::cout<<endl;
return 0;
}
bool repeat = false;
vector<char> letters(m);
char letter;
for(int i = 0; i < m; i++){
do
{
repeat = false;
letter = rand()%26 +97; // generate new random number
for(int j = 0; j<=i; j++) // iterate through the already generated numbers
{
if (letter == letters[j]){ // if the generated number already exists, do the while again
repeat = true;
break;
}
}
} while(repeat);
letters[i] = letter; // assign the unique number
cout << letter;
repeat = false;
}
You repeat the random number generator until you have a unique random number.
And to output your values use i because m is constant and out of bounds:
for (int i = 0; i < m; i++){
cout << letters[i];
}
I think the direct method is to use set in C++. The following solution is done just now utilising set to ensure the unique. Hope it could be helpful.
#include <iostream>
#include <ctime>
#include <set>
#include <random>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
set<char> letters_set;
while(letters_set.size() < m){
char c = rand()%26+'a';
letters_set.insert(c);
}
for(auto c: letters_set)
cout<<c<<endl;
}
A more efficient solution which also ensure the equal possibility for each letter.
#include <iostream>
#include <ctime>
#include <set>
#include <random>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
vector<int> all_letters(26, 'a');
for(int i = 0; i < 26; ++i) all_letters[i] += i;
vector<char> letters_set;
for(int i = 0; i < m; ++i){
int select = rand()%all_letters.size();
letters_set.push_back(all_letters[select]);
all_letters.erase(all_letters.begin()+select);
}
for(auto c: letters_set)
cout<<c<<endl;
}
There is an obvious error in the logic of your code: when you test for repetition you compare to the beyond the end letter only, instead to all those sampled so far. The correct test would be
for(int i = 0; i < m; i++) {
bool repeating;
char tryletter;
do {
tryletter = rand()%26 +97;
repeating = false;
for(auto j=0; j!=i && !repeating; ++j)
repeating = tryletter == letters[j];
} while(repeating);
letters[i] = tryletter;
}
Though this is not the most efficient way to do what you've been asked to do. A more efficient way would be to start with all 26 letters, pick one at random and remove it from the set, then continue to pick and remove random letters. For example
std::string random_letters_without_repetition(std::size_t m)
{
std::string letters;
std::string all = "abcdefghijklmnopqrstuvwxyz";
assert(m <= all.size());
std::random_device r;
std::default_random_engine rng(r());
while(m--) {
std::uniform_int_distribution<std::size_t> uni{0,all.size()-1};
auto index = uni(rng);
letters += all[index];
all.erase(index);
}
return letters;
}
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 .
I'm trying to write a function that will write an array (2D) to file. This is the code below:
#ifndef WRITE_FUNCTIONS_H_
#define WRITE_FUNCTIONS_H_
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void write_array(string name, int rows, int columns, double **array){
ofstream output;
output.open(name, ios::out);
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
output<<array[r][c]<<",";
}
output<<endl;
}
output.close();
}
#endif
When I try to run it in this program here:
#include <string>
#include <iostream>
#include "write_functions.h"
using namespace std;
int main(){
double **array = new double*[10];
for(int i = 0; i < 10; i++){
array[i] = new double[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
array[i][j] = i + j;
}
}
string array_name="home/Plinth/Documents/Temp/array.txt";
write_array(array_name, 10, 10, array);
return(0);
}
It runs perfectly fine, without error or warning, but there is no file created. Did I write something improperly? Am I going about this the wrong way?
You're likely writing in an unexpected directory.
Try to fully specify the path like /home/... (note the first '/') or just write it to a local file like array.txt.
When handling file streams, I prefer using this idiom to detect errors early.
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
std::ifstream input("no_such_file.txt");
if (!input) {
std::cerr << "Unable to open file 'no_such_file.txt': " << std::strerror(errno) << std::endl;
return 1;
}
// The file opened successfully, so carry on
}
I want to reverse a char string in c++.
I wrote this code:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80];
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l; i < l-1; i++, j--){
word[j] = rev[i];
}
cout << rev << endl;
return 0;
}
In terminal it shows some characters like this:
83???uH??? ... Something like this
Your character array rev is not zero terminated.
And istead of to write to rev you are writing to word.:)
word[j] = rev[i];
The loop is also wrong due to condition
i < l-1;
There must be
i < l;
The program can look the following way
#include <iostream>
#include <cstring>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
size_t i = 0;
for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
rev[i] = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is
polymorphism
msihpromylop
Take into account that you can do the same using standard algorithm std::reverse_copy declared in header <algorithm>.
For example
#include <iostream>
#include <cstring>
#include <algorithm>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
*std::reverse_copy( word, word + n, rev ) = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is the same as above
polymorphism
msihpromylop
There are 3 changes I made to your code:
Change 1: Since string length is l, indexing will be from 0 t ol-1.
Change 2: rev will be storing the values from word, not the other way round.
Change 3: A proper string should be \0 terminated.
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80]="";
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l-1; i < l; i++, j--){ //change 1
rev[i] = word[j]; // change 2
}
rev[i]='\0'; // change 3
cout<<rev;
return 0;
}
Working ideone link: http://ideone.com/kIqeNF
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80] = {'\0'};
int i = 0;
int last = strlen(word) - 1;
while(last >= 0) {
rev[i] = word[last];
i++;
last--;
}
cout << rev << endl;
return 0;
}