Loop: Compiles ok, crashes when run | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Loop: Compiles ok, crashes when run

Aim = count lines in the file Code within loop that crashes: _____________________________________ while (file.get(read)){ if (read=='\n') { cout << line_number << endl; line_number++; //when i try to increase line_number it compiles, however when i run the programm windows stops it. } ______________________ full function code: _______________________________ int convert_to_array (char *pFileName) { char read; string sRead; fstream file(pFileName,ios::in); int aLength,line_number; string array[aLength]; if (file.is_open()) { cout << "file again opened " << pFileName<<endl; line_number = 1; while (file.get(read)){ if (read=='\n') { cout << line_number << endl; line_number++; //when i try to increase line_number it compiles, however when i run the programm windows stops it. } sRead=sRead+read; cout << sRead << flush; sRead.clear(); } file.close(); } }

25th Jul 2018, 7:43 AM
George Turdzeladze
George Turdzeladze - avatar
2 Answers
+ 2
Hi George, The problem is in the line you define "string array[aLenght]". Notice that you did not initialize the variable aLenght, thus it stores trash which can be any value even negative. Therefore you are trying to create a variable string with undetermined size. Either you declare something like "string array[1024]", i.e., a constant value or use dynamic memory allocation. Here is a working code: https://code.sololearn.com/cwmIRzLNRvXP/?ref=app
25th Jul 2018, 1:15 PM
Mark
0
thank you very much Mark! Works! i've crunched my brain on this :) what is interesting is that code worked even with this declaration: string array[aLength]; (if you just put line_number; it works, problems started when increment "++" appeared) again many thanks to you!
25th Jul 2018, 2:36 PM
George Turdzeladze
George Turdzeladze - avatar