谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名

can anyone tell me,what is the error in the program?This program is to get the file extension only

本文关键字:程序 用于 获取 扩展名 文件 错误 告诉我 是什么      更新时间:2023-10-16

这个程序的代码是

using namespace std;
std::vector<std::string> get_Extension(std::vector<std::string> arr)
{
std::vector<string>v;
string s;
for(int i=0;i<arr.size();i++)
{
for(int j=0;arr[i].at(j)!='.';j++);
for(int j;j<arr[i].length();j++)
{
s+=arr[i].at(j);
}
v.push_back(s);
s.clear();
}
return v;
}

谁能告诉我,这个程序有什么错误? 它是一个将文件映射到其扩展名的函数。 请参阅此链接以了解此函数的目的是什么: https://edabit.com/challenge/yYEJXuYHHYpkRRoyW

第一个

for(int j=0;arr[i].at(j)!='.';j++);

是一个什么都不做的循环。它不会修改循环之外的任何变量,也没有主体来做任何事情。

在下一行

for(int j;j<arr[i].length();j++)

你有新的j(它与上面不一样!(,它没有初始化,因此有一个随机值。要修复此特定代码,您应该j移出两个循环。

一个更简单的解决方案是使用 std::string::rfind 和 substr。

std::string fileName = "...";
size_t extStart = fileName.rfind('.');
std::string extension = filename.substr(extStart); // including the .

或者,如果您可以使用 C++17(或更高版本(,则可以使用 std::文件系统::p ath::扩展:

std::sting extension = std::filesystem::path(fileName).extension(); //alos including the .

通过在两个for循环中声明j,您实际上是在影子j

你想要的是声明jfor循环之外:

int j;
for (j = 0; arr[i].at(j) != '.'; j++); // get the index of the dot
for (     ; j < arr[i].length(); j++) // iterate the chars of extension
{ ... }

也就是说,当字符串不包含点时,您不会进行错误检查,然后会发生不好的事情。