Hi guys. I was wondering if you could help me with this code. I am trying to open a file and read character by character. The program compiles but when I run it it aborts with an access violation while reading from the file. I made the program output the caracter it was reading and the result is like in the attached image. The file contains only characters no numbers.

ifstream indexFile;
	 vector<char*> vect;
	 string str;
	 char ch, text[30], *cstr;
	 int i = 0;
	 indexFile.open("C:\\test.txt");
	 if (indexFile.fail ())
	 {
		 cerr << "*** ERROR: Cannot open file" ;
		 return EXIT_FAILURE;	// failure return
	 }

	 while(!indexFile.eof())
	 { 
		 indexFile >> ch;
		 cout << ch;
	 	 while(isalpha(ch)) 
		 {
			 text[i] = ch; 
			 i++;
		 }
		 text[i] = '\0';
		 i = 0;
         vect.push_back(text);
	 }
	 
	   
	 indexFile.close();

The problem seems to be in

while(isalpha(ch))
      {
         text[i] = ch;
         i++;
      }

If the first character is an alphabet, it will go on filling the array text with that character and this is almost an infinite loop as isalpha(ch) never fails. As the max. size of text[] is only 300, when the value of i becomes 300, there is automatically an access violation.

Did you forget to read the next ch in the above loop?

And what about white spaces and new lines? You are stuffing all the characters, one by one in a temporary character, but by doing that you are losing all the new lines and white spaces. Therefore you will get an unreadable stream of characters. It would be better to read the file line by line, and then tokenize it. Also with this line:

text[i] = '\0';

you are overwriting the last character in the array, because text is still pointing at the last read character.

Yep that was it :icon_redface: Thanks a lot :)

Yeah I totally forgot about it. Thanks a lot guys for your replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.