首页 > 解决方案 > C++ char数组特性:为什么字符串在数组末尾之前停止?

问题描述

我正在用 C++ 编写程序。其中一部分是这样的:

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

我可以输入小于数组大小的路径,程序按预期工作。我的问题是,为什么fopen正确读取我的路径?我希望它读取数组中的每个字符,但它只读取我输入的内容而不是过去的内容。

我注意到的另一个特点是我可以输入一大串不是有效路径的字符(例如,rrrrrr...),然后,在程序让我再次输入路径后,我可以输入一个较小的序列确实导致有效路径的字符(例如,"C:\file.txt")并且fopen能够“正确”使用有效路径。但是,我希望它将数组中的所有字符用作字符串,其中包括有效路径以及其他先前输入的内容。

我想知道一个数组的特征导致它“正确地”工作,以及这是好事还是坏事。

标签: c++arrays

解决方案


当您使用 cin“输入”字符串时,它会自动在字符串的 n+1 元素处添加一个 '\0'(n 是字符串的大小)。像 cout 或 fopen 这样的字符串操作函数只能读取到该点。为了测试这个理论,你可以输入一个长度为 10 个字符的字符串,例如,然后手动将第 11 个字符更改为其他字符。然后在第 20 个字符处手动添加一个 '\0' 并打印出字符串。你会得到一个 20 字符的字符串,其中从 10 到 20 的字符都是乱码。


推荐阅读