Reputation: 117
I have a code:
`int main() {
int year;
for (year=1880; year<=2011; year++) {
stringstream ss;
ss << year;
string birth = ss.str();
ifstream yob("yob"birth".txt");
}
}`
I want to read in 130 text files with this for loop, and each text file looks like "yob1880.txt" or "yob1975.txt" etc. I know that that ifstream yob("yob"birth".txt") doesn't work I just wanted to illustrate what I wanted to do. How can I add the string "yob" to string year and string ".txt"?
Thank you
Upvotes: 0
Views: 59
Reputation: 127
Use a stringstream
. You can then build a string and call ss.str()
on it to retrieve the string.
E.g.,
std::stringstream ss;
int n = 5;
ss << "file" << n << ".txt";
std::cout << ss.str() << std::endl;
This will write file5.txt
to standard out.
Edit: Just checked the docs, and it looks like std::ifstream takes a C string, not a std::string
, so you should call c_str()
on the resulting string, e.g.,
std::ifstream file(ss.str().c_str());
Upvotes: 1