How to combine lines and INT in C?

I need to form a line inside each loop iteration that contains the loop index i :

 for(i=0;i<100;i++) { // Shown in java-like code which I need working in c! String prefix = "pre_"; String suffix = "_suff"; // This is the string I need formed: // eg "pre_3_suff" String result = prefix + i + suffix; } 

I tried using various combinations of strcat and itoa without luck.

+62
c string
mar 02 2018-11-11T00:
source share
5 answers

Strings - Hard Work on C.

 #include <stdio.h> int main() { int i; char buf[12]; for (i = 0; i < 100; i++) { snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer printf("%s\n", buf); // outputs so you can see it } } 

There are enough bytes in 12 to store the text "pre_" , the text "_suff" , a string up to two characters long ( "99" ), and a NULL delimiter that goes at the end of the C string buffer.

This will tell you how to use snprintf , but I suggest a good C book!

+94
Mar 02 '11 at 19:09
source share

Use sprintf (or snprintf if I can't count) with the format string "pre_%d_suff" .

For what it's worth, with itoa / strcat you can do:

 char dst[12] = "pre_"; itoa(i, dst+4, 10); strcat(dst, "_suff"); 
+5
Mar 02 '11 at 19:08
source share

Look at snprintf or, if the GNU extensions are ok, asprintf (which will allocate memory for you).

0
Mar 02 '11 at 19:09
source share

maybe this works:

 int num = 1; char str1[] = "something"; char str2[] = num; str1 = str1 str2; 

just try it!

-3
Dec 18 '16 at 12:55
source share
 #include < string> #include < sstream> #include < iostream> #include < fstream> int main(){ ofstream fileHandle; stringstream fileName; myInt = 100; fileName << "filename_out_"; fileName << myInt << ".log"; fileHandle.open(fileName.str().c_str()); fileHandle << "Writing this to a file.\n"; fileHandle.close(); return 0; } 

// welcome guys

-eleven
May 19 '13 at 23:48
source share



All Articles