谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
can anyone tell me,what is the error in the program?This program is to get the file extension only
这个程序的代码是
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
。
你想要的是声明j
在for
循环之外:
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
{ ... }
也就是说,当字符串不包含点时,您不会进行错误检查,然后会发生不好的事情。
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 用于将C++代码转换为 Web 程序集的脚本未终止
- 用于检查数字是否有数字或可被该数字的值整除的程序
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 用于创建/注册虚拟存储设备的 IOKit 驱动程序
- LLVM | codegen 用于带有命令行选项的程序输入功能
- 用于检查值是否为其任何参数的帮助程序函数
- 适用于 WebView2 旧版本的示例应用程序
- Ctrl + 不适用于在 Visual Studio 中运行该程序
- C++用于计算移动平均线的程序
- 用于系统程序的 TDD
- 如何将我的小程序转换为用于项目的函数?
- Aysnc 处理程序用于 POCO Websocket 中的传入消息
- GTK 将一个处理程序用于多个小部件
- 无法安装 MPX 运行时驱动程序(用于边界检查)
- C 程序用于使用堆栈检查正确的HTML标签
- readelf 实用程序用于 Visual Studio C++ ABI 和 VS 编译的对象
- 这个opencv程序用于同时从一个文件夹中加载不同的图像,但它只读取一个图像
- 'top'程序用于在屏幕上重新显示数据的技术是什么?