C++ char array characteristic: why does a string stop before the end of the array?

  • A+
Category:Languages

I am writing a program in C++. One part of it is this:

std::wcout << "/nEnter path to seed file: "; char Seed_File_Path[255];//Array for the user to enter a file path std::cin >> Seed_File_Path;  FILE *seed_file_ifp;                        //Creates pointer to FCB for the seed file. seed_file_ifp = fopen(Seed_File_Path, "r"); //opens the file input stream with read permissions.  while (seed_file_ifp == NULL) {//Checks that file was found.     std::wcout << "/nFile not found. Enter a valid path and make sure file exists./n/n";     std::wcout << "/nEnter path to seed file: ";     std::cin >> Seed_File_Path;     seed_file_ifp = fopen(Seed_File_Path, "r"); }//Ends if ifp successful 

I can enter a path less than the size of the array, and the program works as expected. My question is, why does fopen read my path correctly? I would expect it to read in every character in the array, but it reads only what I enter and not past that.

Another characteristic I noticed was that I can enter a large sequence of characters that aren't a valid path (for example, rrrrrr...), then, after the program lets me input a path again, I can enter a smaller sequence of characters that does lead to a valid path (for example, "C:/file.txt") and fopen is able to use the valid path "correctly". However, I would expect it to use as a string all the characters in the array, which include the valid path plus other, previously entered stuff.

I would like to know the characteristic(s) of an array that cause it to work "correctly," and whether that's a good thing or bad.

 


When you "enter" your string with cin it automatically adds a '/0' at the n+1 element of the string (n being the size of your string). String operated functions like cout or fopen will only read up to that point. To test this theory you can enter a string 10 characters long, say, and then manually change the 11'th character to something else. Then manually add a '/0' at say the 20th character and print out the string. You'll get a 20 char string with the chars from 10 to 20 being any gibberish.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: