C++ Problems with write array function - c++

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
}

Related

How to read a 2d triangle array from txt file?

I want to read 2d triangle array from a txt file.
1
8 4
2 6 9
8 5 9 6
I wrote this code. At the end I wanted to print it out if I got the array right. When I run it it does not print the array, but in debug it prints. So there is a problem, but I cannot find it. Sometimes it gives segmentation fault, but I dont understand.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
int main() {
std::ifstream input_file("input_file.txt");
int size{1};
int **arr = (int**)malloc(3*sizeof(int));
int *lineArr = (int*) malloc(size*sizeof(int));
int temp{};
int index{};
while(input_file >> temp){
lineArr[index] = temp;
index++;
if(index == size){
index = 0;
arr[size-1] = new int[size-1];
for(int i{}; i<size; i++){
arr[size-1][i] = lineArr[i];
}
size++;
lineArr = (int*) realloc(lineArr, size*sizeof(int));
}
}
input_file.close();
for(int a{}; a<size-1; a++){
for(int j{}; j<=a; j++){
std::cout << arr[a][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
You can just use vector instead of malloc. Like this:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
int main() {
ifstream input_file("input_file.txt");
vector<string> numbers;
if (input_file.is_open()) {
string line;
while (getline(input_file, line)) {
numbers.push_back(line);
}
input_file.close();
}
for (vector<string>::iterator t=numbers.begin(); t!=numbers.end(); ++t)
{
cout<<*t<<endl;
}
return 0;
}

How do I print out a simple array with numbers 0-99 on the console

I'm new to CS and I'm stuck on a practice problem in arrays where I have to print out an array with numbers 0-99 onto the console. My code right now seems to just create the numbers and print them but not actually put them in the array. I'm just curious how to actually set the elements to the array and then print them because that's the only thing holding me back from finishing the rest of the problem.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = 0;
cout << num << endl;
}
Looks like you are very close! You just need to assign the value of 'i' into your array slot. Hope this helps!
EDIT:
To print the contents of the array you need to iterate back over the array and print each array element.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = i; //assign value of 'i' to array slot
//print array elements
for (int i = 0; i < 100; i++)
cout << num[i]<< endl;
}
read the correct carefully:
#include <iostream>
#include <cstdio> // its C++ equivalent
using namespace std;
int main() {
int num[100];
for (int i = 0; i < 100; ++i)
num[i] = i;
for (int i = 0; i < 100; ++i)
cout << "num[" << i << "]" << num[i] << endl;
}

Why does this code output before even reading input?

My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}
You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.
There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.

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.

Pointer to vector

I've got this code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr;
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
vecptr->push_back(temp);
}
veclen = vecptr->size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<vecptr[i]<<endl;
}
return 0;
}
My compiler(G++) throw me some errors: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...
What's wrong? What can I do to fix it?
The program is still not completely right. You have to initialize the vector pointer and then give it a size and the use it. A full working code could be,
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr = new vector<string>(10);
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
(*vecptr)[i] = temp;
}
veclen = (*vecptr).size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<(*vecptr)[i]<<endl;
}
return 0;
}
Although I have mentioned the size as 10 you could make it a variant.
You need to dereference vecptr here to get the underlying vector:
cout << (*vecptr)[i] << endl;
You will also need to initialize vecptr.