本次的内容为C++如何循环创建一个字符串变量,例如我想打开一系列文件夹,这些文件名字是s1 s2 s3.......我想循环打开或者创建这些。在这样的背景下可以使用如下代码。本次实验是需要注意的一下基础的,实验环境是Ubuntu16的环境编译器支持c++11的,用到了boost库的一些库函数。
上代码:
#include <iostream>
#include <boost/lexical_cast.hpp>//boost头文件
#include <string>//字符串头文件
int main()
{
std::string str1 = "s";
std::string A;
for(int i = 0; i < 10; ++i)
{
A = boost::lexical_cast<std::string>(i);//boost库中的函数,把int准换成string
str1.append(A);//字符串组合函数
std::cout << str1 << std::endl;
}
return 0;
}
编译需要的命令:
g++ boost_string.cpp -I. -std=gnu++11
执行结果:
由于 字符串str1没有在循环中重新赋值,就出现了这种情况,如果在循环执行第一步附上初值就是循环了;
上代码:
#include <iostream>
#include <boost/lexical_cast.hpp>//boost头文件
#include <string>//字符串头文件
int main()
{
std::string str1 = "s";
std::string str2 = str1;
std::string A;
for(int i = 0; i < 10; ++i)
{
str1 = str2;
A = boost::lexical_cast<std::string>(i);//boost库中的函数,把int准换成string
str1.append(A);//字符串组合函数
std::cout << str1 << std::endl;
}
return 0;
}
执行结果: