递增变量名C++
我做了一些研究,没有找到具体的答案,是否可以增加变量名和/或文件位置? 有没有可能这样做:递增变量名C++,c++,C++,我做了一些研究,没有找到具体的答案,是否可以增加变量名和/或文件位置? 有没有可能这样做: for(int i = 0; i<5; i ++) { name1->readName("filelocation/name1.txt"); } std::string strExt = ".txt"; std::string strPath = "D:\\Data\\test"; std::string strFullPath = strPath + strExt; for(int
for(int i = 0; i<5; i ++)
{
name1->readName("filelocation/name1.txt");
}
std::string strExt = ".txt";
std::string strPath = "D:\\Data\\test";
std::string strFullPath = strPath + strExt;
for(int i(0); i < 5; i++){
std::cout << strFullPath << std::endl;
strPath[strPath.length() - 1]++;
strFullPath = strPath + strExt;
}
并在每个循环周期中增加一个name1和name1.txt?那么在secon循环中,name1变成了name2?
感谢您提前提供的任何帮助变量名-否。表示文件名的字符串文字-是。使用该函数的一个简单示例:
#include <iostream>
#include <string>
void foo(const std::string& s) {
std::cout << s << '\n';
}
int main() {
for (int i = 0; i < 5; i++) {
foo("filelocation/name" + std::to_string(i) + ".txt");
}
}
您可以使用:
for ( int i = 0; i < 5; i++)
{
char filename[200]; // Make it large enough for your needs.
std::sprintf(filename, "filelocation/name%d.txt", i+1);
name1->readName(filename);
}
您可以这样做:
for(int i = 0; i<5; i ++)
{
name1->readName("filelocation/name1.txt");
}
std::string strExt = ".txt";
std::string strPath = "D:\\Data\\test";
std::string strFullPath = strPath + strExt;
for(int i(0); i < 5; i++){
std::cout << strFullPath << std::endl;
strPath[strPath.length() - 1]++;
strFullPath = strPath + strExt;
}
但正如你所看到的,循环的时间稍微长一点,然后你会让它循环回来。所以做一些更大的事情,然后只是增加直到最后一个字符或数字,然后添加新的字母,等等
准确点!不是递增变量名,而是递增变量值。所以我在我的代码中增加strPath中的值,而不是strPath本身strPath,strPati,strPatj,strPatk。。。。因为C++不允许这样的事情。你应该把这些对象存储在一个容器中,比如数组、vector等等,这样你就可以使用索引而不是名字序列访问每个对象。假设你有对象叫名字,这是我的C++回答:
std::vector<Name> name;
int N = 3;
for(int i = 0; i < N; i++) {
std::stringstream ss;
ss << "filelocation/name" << i << ".txt";
img.push_back(Name());
img[i].readName(ss.str());
}
您正在寻找一个arrayPost半可编译代码,该代码说明了您的问题。C++中的名字在编译时被固定,在运行时被丢弃。变量名- NORE字符串表示文件名。是的。如果你从NAME1到NAME5有编号的变量,通常是你做了错事。这就是数组的用途。谢谢大家的夸奖@Ron,我如何增加表示文件名的字符串文字?