i have to generate filenames
text file names as
c:\\blabla.. saved(counter).txt
the counter is an integer value
i cant do it
i cant generate filename like dat
i declared a string c:\\blabla
second counter
third .txt
now i have to concatenate all three in a string variable
and this has to be generated in a for loop....

can anybody tell me method to do it...asap.thank you

Dani AI

Generated

asked how to build filenames like c:\blabla.. saved(<counter>).txt in a loop and asked about the counter range. Two reliable, simple approaches follow: modern C++ string construction and a safe C-style format into a fixed buffer. Both handle negative values; zero-padding or width control is shown in the notes.

Example (modern C++, recommended):

#include <string>
#include <iostream>

for (int i = 0; i < 10; ++i) {
    std::string filename = "c:\\blabla.. saved(" + std::to_string(i) + ").txt";
    std::cout << filename << '\n';
    // open or write the file using 'filename'
}

Example (C-style safe formatting):

#include <cstdio>

char filename[260];
for (int i = 0; i < 100; ++i) {
    std::snprintf(filename, sizeof(filename), "c:\\blabla.. saved(%d).txt", i);
    // check return from snprintf for truncation before using filename
}

Notes and cautions: string literals require backslashes to be escaped (\\) or use raw string literals. std::to_string handles negative values; std::ostringstream or std::format (C++20) allow padding like zero-fill when filenames must sort lexically. When using snprintf, always check the return value to detect truncation and pick a buffer size large enough. For real projects, prefer std::filesystem::path to build and manipulate paths safely (see std::to_string and std::filesystem::path).

Recommended Answers

All 2 Replies

problem redefined:
Strcat() to concantenate an int to char array


How to concantenate a number to a char, for example, concatenate a number to a filename, a file that has been created. I'm aware of strcat(), but the tricky part was creating an array for the filename and then appending a number to it..

First is the number -10 < n < 10 ? Is it within -10 and 10 but not including 10?

Or can it be any number?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.