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.
Related
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 3 years ago.
Improve this question
I have a pointer array of Word (objects) and I have to assign another object of type Word to this objects array.
Using this two lines of code I put the new object w inside my objects array (word).
Word w = Word(new_word, len);
this->word[index - 1] = w;
Then I print my objects array and everything comes out right
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 1
After "End of function" we return to the main class that call to another function.
This function print the objects array again but now the function does not print the w object that I insert in the previous function.
Second function
for (int k = 0; k < this->len; k++) {
cout << this->word[k].getChars() << endl;
} // End of function 2
Can anyone explain to me why this is happening and how it can be arranged.
Though it's difficult to be certain (since we don't have the rest of the function to look at), it seems that you may have a dangling pointer issue.
When you declare Word w = Word(new_word, len); in your function, you're declaring it as a local variable, placing it on the stack. Adding this to the array doesn't cause any issues when you're still in the function, but once you return from where you came, the function's memory - including Word w - is destroyed. When you try to access that memory location again by printing it from the array, you're looking for a variable that no longer exists, and thus get undefined behavior.
Luckily, you're using c++, and heap memory management is fairly well supported! I would consider implementing word as an array of pointers. If you then try something like this...
Word *w = new Word(new_word, len); //use "new" to create an object on the heap - persistent after you leave the function!
this->word[index - 1] = w; //make sure this->word is now an array of Word*; it seems to currently be an array of Word
...you may find the problem solved. Just don't forget to free it when you're done!
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 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!
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).
This question already has answers here:
when do we need to pass the size of array as a parameter
(8 answers)
Closed 6 years ago.
I'm currently working on a project where I want to convert the entries of a CSV file into a vector of Objects. Therefore I have written a function, which converts an array of structs in a vector. The problem is that right now my function only works if the user enters the right size of the array as an additional parameter but if he enters a higher number an exception is thrown because the function is trying to read from an array entry that doesn't exist. Now I want to know if there is anyway that I can determine the size of the array of structs in my function. I have already tried sizeof(array)/sizeof(array[0]) but that doesn't work.
Here is the function I'm talking about:
BANKMANAGEMENT_API int initAccounts(ACCOUNT accArray_[], const int numOfAcc_)
{
BankmanagementClass *myBankmanagement = BankmanagementClass::createBankmanagementClass();
for (int i = 0; i < numOfAcc_; i++)
{
ACCOUNT acc = accArray_[i];
Account* newaccount = Account::accountStruct2Obj(&acc);
myBankmanagement->setNextAccountId(myBankmanagement->determineNextId(newaccount->getAccountId(), myBankmanagement->getNextAccountId()));
myBankmanagement->addAccount(newaccount);
}
LogInfo("Account Vector was initialized with data from Csv File.");
return 0;
}
I want to get rid of the numOfAcc_ parameter so that the user can't enter the wrong size.
It's for a dll with C interface.
There is no way to determinate the size of the array. If you have under control how accArray is filled you could use an end marker and check this condition in the for loop.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am making a simple Lottery program - and am struggling with implementation. I have a class called 'Ticket Line' this class simply holds 6 numbers that the player is playing a lottery for.
What I want to do, is generate 6 randomly (got function for this already) and then store that in another class as values. To do this, I am using the following code:
class Draw
{
private:
int drawID;
TicketLine* DrawnNumbers;
bool drawn;
}
When a Draw is completed I want to generate the Random Numbers ( from the TicketLine class) and then for the Draw to be able to store those numbers into its Draw File.
How would I be able to access the functionality of the DrawnNumbers class - and store the results from the getTicketNumbers.getTicketLine()function.
int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();};
The program crashes the following code:
//int *ptr[6] = getTicketNumbers();
int *ptr[6] = getTicketNumbers();
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
TicketLine class:
private:
int select[6]; //Array of Ticket Numbers.
int* getTicketLine(void) { return select; };
I am willing to offer a couple of virtual beers to the solution. I am as yet to find a good online pub - if you know of one then please do let me know :-)
Thanks,
Without knowing any more, this line:
int *ptr[6] = getTicketNumbers();
is very suspect.
Why? Well, we haven't seen the implementation of getTicketNumbers so we don't know if it's actually allocating memory for 6 and returning such an array.
Also, you are printing the values of pointers here:
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
Where, if you intended to actually print the int values, you'd say something like this:
for (int x = 0; x < 6; x++){
cout << *(ptr[x]);
}
My guess is that you are either:
Going out of bounds of an array that was (not) allocated, or,
Modifying actual pointer values somewhere instead of the integers they point to (as indicated by your lack of dereferencing ptr[x] in your print statement)
Edit
With more information, it seems you probably meant to say this:
int *ptr = getTicketNumbers();
instead of this:
int *ptr[6] = getTicketNumbers();
You should probably be doing some sanity checks as well to make sure that select is actually filled before calling that function (maybe giving it a default value of {0,0,0,0,0,0} in the constructor)
DrawnNumbers doesn't appear to be pointing to anything yet. It's a pointer, but to what?
Also, be careful about returning arrays that way. If the object or stack frame that the array resides in goes away, you'll be left pointing to bad things.