void BinaryTree::InitializeFromFile(string Filename){
ifstream inFile;
treenode* Freq[256];
inFile.open(Filename.c_str(), fstream::binary);
if(inFile.fail()){
cout<<"Error in opening file "<<Filename;
return;
}
for(int i=0;i<=255;i++){
Freq[i]->weight=0;
Freq[i]->data = '0'+i;
Freq[i]->LChild = NULL; Freq[i]->RChild=NULL; Freq[i]->Parent=NULL;
}
char c;
inFile.get(c);
while(!inFile.eof()){
Freq[c]->weight ++;
inFile.get(c);
}
}
I'm getting the Access Violation Exception in the for loop. Even when I comment out certain lines it'll give me an error on the next line in that loop.
Edit: Also is the line Freq[c]->weight ++; valid? Can I go to a specific part of the array based on the char value?
You seem to never initialize your Freq table. It contains random pointers. Dereferncing an uninitialized pointer leads to undefined behaviour.
You ought to add Freq[i] = new treenode before Freq[i]->weight=0;.
Related
I've got a GUI with a TabControl. Each new TabPage is created via a new Thread. I want to call this->tabControl->TabCount, but the tabControl is owned by a thread other than the one I'm calling from. Therefore, I need to Invoke a delegate. However, all the examples I find online show printing to std::cout from each of the delegate methods. I need a return value, in this case an int.
delegate int MyDel();
int InvokeTabCount()
{
if (this->InvokeRequired)
{
MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
auto temp = this->Invoke(del); // can't just "return this->Invoke(del)"
return temp; // Invoke() returns a System::Object^
}
else
{
return this->tabControl->TabCount;
}
}
void CreateNewTab()
{
// do stuff
this->tabControl->TabPages->Insert(InvokeTabCount() - 1, myNewTab); // insert a tab
this->tabControl->SelectTab(InvokeTabCount() - 2); // OutOfBounds and tabPageNew
}
System::Void MethodToAddNewTabPage() //actually a click event but whatever
{
System::Threading::Thread^ newThread =
gcnew System::Threading::Thread(
gcnew System::Threading::ThreadStart(this, &MyTabControl::CreateNewTab));
newThread->Start();
}
Currently, my InvokeTabCount() method is returning -1 when I simply this->Invoke(del) without returning it. And I am unable to return it because my method expects to return an int instead of a System::Object^ which is what Invoke() returns. However, when debugging I find that auto temp contains the value 2 which is correct. And temp->ToString() contains the value "2" which would also be correct.
How do I return this->Invoke(del)?
Do I need to set the value of a global variable from within my InvokeTabCount() method? I suppose I could find a way to translate from System::String^ to std::string to utilize std::stoi(), but that seems like an odd workaround.
Current solution:
delegate int MyDel();
int InvokeTabCount()
{
if (this->InvokeRequired)
{
MyDel^ del = gcnew MyDel(this, &MyTabControl::InvokeTabCount);
auto temp = this->Invoke(del);
return int::Parse(temp->ToString());
}
else
{
return this->tabControl->TabCount;
}
}
The result is an integer, boxed and contained in an Object^ reference. You should be able to simply cast it to int.
If you want to be extra safe, do a null check and verify that temp->GetType() returns int::typeid, but that's probably overkill since you're creating the delegate (still in the typed form) right there.
I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly
I have my code as below and I'm getting ConcurrentModificationException, particularly in the line for (String file : files)
I don't change anything for the "file" when doing iteration, so why the exception will be caused and how should I avoid it? Thanks for any suggestion!
int getTotalLength(final HashSet<String> files) {
int total = 0;
int len;
for (String file : files) {
len = getLength(file);
if (len != Long.MIN_VALUE) {
total += len;
}
}
return total;
}
int getLength(String file) {
int len = Long.MIN_VALUE;
if (file == null) {
return len;
}
File f = new File(file);
if (f.exists() && f.isFile()) {
len = f.length();
}
return size;
}
Refering to you comment, declaring final HashSet<String> files makes variable files finale - that means that you cannot assign another object to this variable inside this variable's scope. HashSet itself is mutable object and can be modified - it has nothing to do with final modifier (reference to the set object itselt is still the same).
If you want to work concurently on same object (same hashset) use synchronized blocks or methods.
Generally speaking, you cannot modify collection (in same or another thread) that are beeing iterated with for loop in for-each alike variant.
I have a text file, for example : file.txt, I want to read a line, for example line 7, have any way to read directly line 7 without reading other lines? I want to save memory from this work.
Because of the way JME been cut down you cannot do this. You would have to read whole file. Only other way, but may not be well suitable is to read the file , store it in RecordStore new entry per line, but is it really worth...
I think it is possible however you need to use a hashtable which might result to more heap usage.
Anyway, first, the contents of the text file should be stored in a char array. Then, second, the contents of the char array must be moved to the hashtable.
Each line in the text file is separated by a new line. In the char array, the new line (maybe) is translated to '\n'. Concatenate the characters in the array until the new line character is reached. The concatenated characters (minus '\n') will form the string in the first line. There should also be a counter here which should have been initialized to 0 (or 1, whatever you prefer). Save the text to the hashtable; The value will be the string that has been created and the key will be the counter. Increment the counter afterwards. Repeat this process for the remainder of the array until the end of file is reached.
With the hashtable, you can now get the string at line 7 without going through the other lines. Well, basically, each line has been read once. But, at least, you don't have to traverse each line once they have been stored in the hashtable.
Like what I have said earlier, doing this might increase heap usage especially if the text file is very large.
[And, by the way, sorry for the very late response. This is my first time here (I mean I just registered and answered this question) :D ]
Common Code
private String readLine(InputStream _inStream, int lineNum)
throws IOException {
if (null == _inStream) {
throw new IOException("Inputstream null.");
}
if (lineNum < 0) {
return ("Cannot read line a number " + lineNum);
}
final StringBuffer buf = new StringBuffer();
byte c;
int curLine = 1;
while (((c = (byte) _inStream.read()) != -1)) {
//System.out.println((char)c);
if (c == '\n') {
++curLine;
if (curLine > lineNum) {
break;
} else if (curLine < lineNum) {
continue;
}
} else if (curLine != lineNum) {
continue;
}
buf.append((char) c);
}
if (0 == buf.length()) {
return null;
} else {
return buf.toString().trim();
}
}
.
private String readLineWithSkip(InputStream _inStream, long skipCharacters)
throws IOException {
if (null == _inStream) {
throw new IOException("Inputstream null.");
}
if (skipCharacters < 1) {
return ("Cannot skip stream of " + skipCharacters + " characters");
}
final StringBuffer buf = new StringBuffer();
byte c;
_inStream.skip(skipCharacters);
while ((c = (byte) _inStream.read()) != '\n') {
//System.out.println((char)c);
buf.append((char) c);
}
if (0 == buf.length()) {
return null;
} else {
return buf.toString().trim();
}
}
.
InputStream inStream = null;
int fileLength = 39;
int skipCharacters = 10;
int lineNumber = 3;
String myLine = "No line read.";
try {
inStream = Class.class.getResourceAsStream("/test.txt");
if (null != inStream) {
inStream.mark(fileLength);
//For Approach II
myLine = readLine(inStream, lineNumber);
inStream.reset();
//For Approach I
myLine = readLineWithSkip(inStream, skipCharacters);
}
} catch (SecurityException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
inStream = null;
System.out.println(myLine);
}
.
Approach I: Map the line number with no of cumulative characters
Run the file through a code that maps the line number with the last of charater in that line from the 0th position of the file (to be used as skip() value) all +2 ('\r\n\') for each line. You can store this Mapping table either at the start or at the end of the same file.
The run the above common code with method readLineWithSkip(inStream,
skipCharacters); ONLY and judiciously commenting other method calls.
Points to Consider:
Skips to the desired position in the inputstream
Has an overhead of parsing the file and storing the mapping table.
.
Approach II: Read each line till the Nth line is read
The run the above common code with method readLine(inStream,
lineNumber); ONLY and judiciously commenting other method calls.
Points to Consider:
Slow since it has to read each character till it reaches the desired line
No overhead of parsing the file and no storing of the mapping table.
I would like to further simplify the problem of reading the chars without requiring any mapping of characters with line numbers.
...
Form form=new Form("filename");
InputStream fin=fconn.openDataInputStream();
StringBuffer buf =new StringBuffer();
int c;
int counter=-1;
while((c=fin.read())!=-1)
{
counter++;
if(counter==23)
{
form.append(buf.toString());
buf=null;counter=0;
continue;
}
buf.append((char)c);
}
if(counter<23 && counter>=0) // write the skipped chars between the last number read and the end of file
{
form.append(buf.toString());
buf=null;counter=0;
}
fin.close();
...
Hope this would help others.
I'm trying to replace a string in an array(update array) with a string found at an index of array(other array). Both arrays are initialized in init and i can nslog them in this method. if [str isEqualToString:[otherArray objectAtIndex:i] i want to return true/YES
but the line: [updateArray replaceObjectAtIndex:i withObject:str]; is giving bad access to program. (its only a console program) "Program received signal: “EXC_BAD_ACCESS”.
any suggestions appreciated, thanks trev
-(BOOL)checker:(NSString *)str {
NSLog(#"update arrayobject at %d is %#",0, [updateArray objectAtIndex:0]);
NSLog(#"otherArray size is %d",[otherArray count]);
NSLog(#"str iput is %#",str);
int i;
for (i=0; i<[otherArray count]; i++) {
if ([str isEqualToString:[otherArray objectAtIndex:i]]) {
[updateArray replaceObjectAtIndex:i withObject:str];
return TRUE;
}
}
return FALSE;
}
once check your array is it allocated or not properly..i think there is nothing more than that thing..