Strings concatenation

Hi guys,
I'm new to c++ programming and I need to fulfill a vector of n strings with strings which are named in a similar way. Suppose that my strings are:
file1.txt
file2.txt
file3.txt etc...
I need my a vector like:
vector <string> files = {"file1.txt","file2.txt","file3.txt"}
This is what i managed until now:

#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>
using namespace std;

int main(){

int filenumber;
cout << "Insert the number of files: " << endl;
cin >> filenumber;

string s1;
cout << "Insert the first part of file names: " << endl;
cin >> s1;
vector <string> files(n);

for(int i=1; i<n; i++){
char str[80];
strcpy(str,s1);
strcat(str,to_string(i))
files[i-1]= str;
}

for(string c : files)
cout << c << endl;

return 0;

}

But I still have issues throughout compilation. Can you fix my code? Thank you so much.
But I still have issues throughout compilation.

Obviously, you wouldn't be here otherwise.

Do you know the difference between a C++ std::string and a C-string?

Can you fix my code?

No, I won't "fix" your code, but I will give you hints as to what you must do.

Hint 1: You seem to know about C++ strings so stick with them. And when you do stick with std::string there will be no need of the C-string functions like strcat, and strcpy.

Also remember that in C++ vectors/arrays start at zero not one.

Do you realize that you're only trying to enter one "file name"?

Lastly for now, in future please use code tags (the <> icon to the right of the editor window) and post all of your error messages, along with the code, exactly as they appear in your development environment.


The only input you need is the number of files.
Once you have that you use a simple for loop to build the filename and add the filename to the vector.

Inside the for loop you only add the current number to a string with the value "file". Once you have done this you add ".txt to the string. Finally you add the string to the vector.

Vectors have a function push_back.
To add another string to string you can either use += or use append
Topic archived. No new replies allowed.