How do i set a function to a constant variable? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
It's been a while since I have worked in C++, I am helping a friend.
Is there a way without pointers return number of lines to a const int for use in a for loop?
I know I can do it with pointers but he has not learned them in class yet and I am not morally allowed to teach him anything the professor hasn't.
Example:
int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}
EDIT: my fault I was moving fast to code this thing. I am helping him today I want to have a finished project so I can work off of it while helping him. The reason I need a constant int is so I can set array to that size not just for a for loop. the array is the problem.

You can initialize a const int just the same as you would initialize a regular int. The difference with a const int is that you cannot re-assign after initialization.
const int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}

In the simplest case you're just looking for the number of '\n' characters in the file.
So let's say that you've successfully opened the file to: ifstream pFile then you can use an istreambuf_iterator to count those:
const auto numLines = count(istreambuf_iterator<char>(pFile), istreambuf_iterator<char>(), '\n')
A couple comments here:
The this count operation will consume everything in pFile's buffer, meaning you'll need to call pFile.seekg(0, ios_base::beg)
Picking and choosing values to read from an ifstream indicates a bad smell in code. It's likely that the file format was improperly conceived, or that the program will subsequently need to re-stream the remainder of file contents. The 2nd option seems to be true in your case, as you seek to illegally set the size of an array with a value found at runtime:
The reason I need a constant int is so I can set array to that size
EDIT:
When you say you want to use numLines to "right an array"[sic], my assumption is that the only reason that you would have needed your array to be that size is that you're going to stream each line from a file into your container, that is you're going to stream the entire file once to calculate the size then stream the entire file again to populate your container. Here's what you should do instead:
vector<string> lines;
for(string line; getline(pFiles, line);) {
lines.push_back(line);
}
Now lines will contain your entire file, with each element being a line. If numLines would have been important to you, instead you can use size(lines).

Related

C++ Reading Characters from Text File to Dynamically Allocated Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am relatively new to C++, and I am attempting to read sequenceofchars from a text file into a char array that is dynamically allocated. My code is as follows:
while (file.get(c))
{
if (c =='\n')
continue;
char *temp = new char[i++];
arrayA = new char[i++];
arrayA[i] = c;
delete [] arrayA;
arrayA = temp;
}
And the text file format is as follows:
>NameOfChars
sequenceofchars
This is obviously horribly broken, but I've struggled to figure out the exact methodology one would use to go through this. I know about the Vector class, but I am unsure about how to go about using that if that is the preferred method for reallocating arrays on the heap. Any help would be greatly appreciated. Thank you.
I think you should definitely take a look at the vector class since it would make your code a lot cleaner. Here is a small (untested) code sample of how to use it:
#include <vector>
std::vector<char> my_vector;
while (file.get(c))
{
if (c =='\n')
continue;
my_vector.push_back(c);
}
For more information please check http://www.cplusplus.com/reference/vector/vector/push_back/
A raw array isn't dynamically allocated; hence using an STL container like vector would be better.
ifstream inf;
char c;
vector<char> charVec;
while (inf >> c)
{
charVec.push_back(c);
}

How to dereference an array element (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.
int size = 5;
string* myArray = new string[size];
I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?
string line;
myArray[0] = "Hello";
line = *myArray[0];
Edit:
I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.
void MyClass::setLine(string line)
{
myLine = line; /*This is a private variable in MyClass*/
}
///////////////
MyClass* elements = new MyClass[size];
elements[0].setLine(myArray[0]);
I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.
If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.
Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.
As such, no extra dereference is needed. Just drop the asterisk in the failing line.
Valid code will look like
string line;
myArray[0] = "Hello";
line = myArray[0];
By the way you could use class std::vector instead of the array if you are going to add or remove elements from the collection.
For example
std::vector<std::string> myArray;
myArrray.reserve( 5 );
myArray.push_back( "Hello" );
line = myArray[0];

How to read input from header file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a header file abc.h
//abc.h
unsigned int *get(void)
{
static unsigned int input[] =
{
1,
2, 2,
4, 5,
6, 7
};
return input;
}
Now, i want to read this input(from header file,not from some text file) into my main cpp file say xyz.cpp
I am thinking of using an array to access these elements,but i don't think it will work.
int arr[6];
arr=get();
The first element is number of test cases n,the second and third element are dimensions of 2-D array and the rest of the elements are the values of 2-D array.So i need to input value of n,rows,columns and values for 2D array arr[rows][columns]
Any ideas on how can i achieve this?
EDIT: I seriously can't figure out why this question is getting downvoted.
I agree this is not a good implementation,but I have been given an input header file and i can read data only through this header file!!
If you able to compile your programm with this file, you does not need to read anything. This array and it values will be compiled into your programm and you can access them right in place
Your xyz.cpp file should look like:
#include "abc.h" // given abc file located in the same directory
int main(){
unsigned int * myArrayPtr = get();
// here comes some processing and, if you want, reading values from this array;
unsigned int numberOfCases = myArrayPtr[0];
unsigned int * dimensionsArrayPtr = myArrayPtr + 1;
unsigned int xArraySize = dimensionsArrayPtr[0];
unsigned int yArraySize = dimensionsArrayPtr[1];
// and etc.
// Most interesting part to represent those values as two dimensional array
// I left to you :)
return 0;
}
Also, you should remeber that this trick could work only because array in header file declared as static. Otherways your programm would have undefined behavior.
One more also. If your function body defined in header file, you should declare it inline.
As long as this header included only on one cpp file - its all right. But when it will included to more the one code file, you will get already defined linker error.
I recommend you to learn more about pointers in cpp. This article is fine enough http://www.cplusplus.com/doc/tutorial/pointers/
About static keyword - to fully understand this example - there is fine answer on SO itself
The static keyword and its various uses in C++

error in reading and writing in files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This program works but prints garbage values at the beginning (ch=2) and prints the same output twice.
I am using this for my project.It contains more data and there i used a single object instead of array of objects.It didnt work.Each object of array stores a set of data.
#include<iostream>
#include<fstream>
using namespace std;
class rw //a class containing some data
{
public:
int n;
char a;
};
int main()
{
int i;
rw r[2]; //an array of objects
int ch;
fstream f1;
f1.open("file1.txt",ios::in|ios::out|ios::ate);
cout<<"1-read,2-write";
cin>>ch;
f1.seekp(0,ios::beg);
if(ch==1)//for saving
{
r[0].n=1;
r[0].a='a';
f1.write((char*) &r[0],sizeof(r[0]));
r[1].n=2;
r[1].a='b';
f1.write((char*)&r[1],sizeof(r[1]));
}
if(ch==2)//for reading
{
f1.seekg(0,ios::beg);
while(!f1.eof())
{
i=0;
cout<<r[i].n<<r[i].a;
cout<<"\n";
f1.read((char*)&r[i],sizeof(r[i]));
i++;
}
}
system("pause");
return 0;
}
Change following code
cout<<r[i].n<<r[i].a;
cout<<"\n";
f1.read((char*)&r[i],sizeof(r[i]));
to
f1.read((char*)&r[i],sizeof(r[i])); // Moved before printing
cout<<r[i].n<<r[i].a;
cout<<"\n";
You are outputting data then reading from the file, instead you should read and then print. Printing before reading is the reason for getting garbage in first run of loop. I think you moved the reading below to avoid double printing of last record. Continue reading to understand how to avoid double reading.
You should avoid using while (!f1.eof()), as it will print last data twice.
Better use while(f1.read((char*)&r[i],sizeof(r[i])));
Unrolling the eof version of loop for 2 inputs
while(!eof) // true
read first data
print first data
while(!eof) // true
read second data // read all, but was succesful and eof not set
print second data
while(!eof) // true
Try to read // Could not read, eof set
print data // Reprinting second data
while(!eof) // false
Don't use while (!f1.eof()), it will not work as you expect it to, because the eofbit flag isn't set until after you try to read from beyond the file. Instead do e.g. while (f1.read(...)).
Also be careful with a loop like this without bounds checking. If the file is not correct you might write out of bounds of the array r.

Array of classes won't hold new value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Okay so I'm trying to parse information from a file and I have this loop that reads in an unknown amount of 5 number strings that are separated by new lines. ProfDB is simply an array that holds objects of a class Professor. That class has a method (addPrevCourse()) that adds a Course object to an array of courses within that class. CRNDictionary is a function that takes a string and returns a course object, based on that string. Here are the code snippets:
Main:
ifstream in;
in.open("File.txt");
string CRNHash = "";
while (CRNHash != "!ENDLIST"){
in >> CRNHash;
(*ProfDB[used]).addPrevCourse(CRNDictionary(CRNHash));
addPrevCourse:
void Professor::addPrevCourse(const Course& newCourse)
{
int i = 0;
while (i < 8){
if (Courses_Taught[i].getCRN() == "0"){
Courses_Taught[i] = newCourse;
}
i++;
}
}
CRNDictionary:
Course CRNDictionary(string CRN){
//search course list for the crn passed, temp implementation
if (CRN == "12345")
return Course("Test", "12344");
else if (CRN == "13254")
return Course("Test2", "13254");
else
return Course("Test2", "BLAH");
}
The problem is that when I run the program, and print the Professor's array (Which holds the 5 char strings), all the values are shown as 12344 (The first object from CRNDictionary), even though the file has 5 different values. I have verified that CRNHash is getting scanned in correctly, but can't figure out why the value won't change that gets added to the array.
It's because after the first pass of addPrevCourse all the array items are filled with the first input causing the if inside that function to always be false on following passes. What you need to do is either add a break in the while when the condition is true, or keep a member counter in Professor to know which is the next empty array cell.