Input vector and store into txt file

I have been searching for a while and would like an example of the following.

1) Create a vector
2) Single Vector accepts int and string (is this possible?)
3) Input vector details (cin) through command prompt
4) The information that has been input is then stored to a txt file.

I have managed to create a vector and input the information it needs into the compiler. However, I simply do not understand how to do step 3.

I would appreciate it a example is posted along with an explanation of how it works.

1
2
3
4
std::ofstream file("this.txt"); 
std::string i;
std::cin >> i;
file << i;


Take a peek at the tutorial this site has! This is stuff that everyone should know. These are called "input / output streams".

Also if you are only putting a number into a file, they are indifferent to strings.

also
I have managed to create a vector and input the information it needs into the compiler

What do you mean by "into the compiler", I think you are confused. The compiler is only responsible for giving errors and creating the executable, I think you mean the code.
Let me rephrase I want the user to be able to input the required information into the command prompt and the information to be stored to a txt file.

What I dont want is for the information entered to already exist example below.

1
2
int foo[5];         
foo[2] = 75;  


Instead I want to create an empty vector. I would also like a single array to accept int and strings.

create vector
vector contains 3 int value and 1 string
user inputs 3 int and 1 string through command prompt
if the information is correct (no double, no int instead of string, etc,)
then save to txt file (the reason I want to save it to a txt file is to allow other users to retrieve the information)
else retry and input again

I've been searching for quite a while but no site seems to have the solution to the issue I am facing, maybe I am keying in wrong keywords, could you refer me to any site that can assist me regarding this matter?

By the way I apologize for the late reply.
For instance I found this example

1
2
3
4
5
6
7
8
9
10
11
12
13
const string fileName = "stations.txt";

	{
		const vector <film> favourites = { { "Au hasard Balthazar", "Bresson", "1966", "French" },
		{ "Stalker", "Tarkovsky", "1979", "Russian" },
		{ "Smultronstället", "Bergman", "1957", "Swedish" },
		{ "Ikiru", "Kurozawa", "1952", "Japanese" },
		{ "Werckmeister harmóniák", "Bela Tarr", "2000", "Hungarian" },
		};

		std::ofstream file(file_name);
		for (const film& f : favourites) file << f;
	}


But instead of "pre defining " (not sure how I should refer to the values existing before hand). I want the user to input the code below themselves and through the command prompt.

 
"Stalker", "Tarkovsky", "1979", "Russian" 


Hope I made everything clear.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <fstream>
#include <vector>
#include <cctype>
using namespace std;

struct THING       // for want of any other information
{
   int num;
   string text;
};


//--------------------------------------


THING getThing()
{
   THING thing;
   cout << "Input integer: ";   cin >> thing.num;
   cout << "Input string:  ";   cin >> thing.text;
   return thing;
}


//--------------------------------------


ostream &operator << ( ostream &strm, THING thing )
{
   strm << thing.num << "  " <<  thing.text << '\n';
   return strm;
}


//--------------------------------------


int main()
{
   vector<THING> things;                         // If you want to process them in your program
   ofstream out( "things.txt" );                 // The file to be written to
   char ans = 'y';

   while ( tolower( ans ) == 'y' )
   {
      THING thing = getThing();
      // You could call a validation routine here (or during input)

      things.push_back( thing );                // keep in memory
      out << thing;                             // and/or write to file

      cout << "Add more data? (y/n): ";   cin >> ans;
   }

   out.close();
}


Input (console):
Input integer: 1
Input string:  wife
Add more data? (y/n): y
Input integer: 2
Input string:  kids
Add more data? (y/n): y
Input integer: 1
Input string:  cat
Add more data? (y/n): n


Output (file things.txt)
1  wife
2  kids
1  cat

For instance I found this example

That is not "a vector of ints and strings".

That is "a vector of films". One film is apparently created from four strings.
Note that "1966" is not a number; it is a string. An int would be 1966.

lastchance shows a THING. It is created from an int and a string. Exactly "int and string" and in that order, no "or" about it.
@Ghettoburger, (EDIT - have you just removed a post? I'm replying to it here.)
I assembled a structure (here, called THING) to hold a collection of related items of different types. It's probably not precisely what you want (you probably need more integers), but you should get the gist. It's basically a user-defined type. There is more about such things in the excellent tutorial on this site:
http://www.cplusplus.com/doc/tutorial/structures/

Now, suppose I want to write just one of those structures to a file - more specifically, in C++ I write to a stream that is connected to a file. You can find a lot about it here:
http://www.cplusplus.com/doc/tutorial/files/

It is convenient to write a routine that will work for ANY output stream (an ostream), even the standard cout if I wanted. So I could just do this through a function declared as
void output( ostream &strm, THING thing )
and it will be called from main() as just
output( out, thing);
In fact that is precisely what I did at first - but I didn't post it. However, all this routine does is write one THING to file. If I was to write a single integer N to this output stream I would probably write
out << N;
So all I have done with the routine that you highlight is allow me to do the same for my user-defined type instead of an integer:
out << thing;
The posh name for this is overloading the insertion operator (you can google that phrase) - I am basically writing a routine allowing the normal << operator to work for my own type; without it the system wouldn't know what to do.

If you want to change the line in main() to
cout << thing;
then you will find that the output can go to the normal screen output stream instead of to file. Try it.

I have been told on this forum that overloading operators is too much for beginners. However, I personally think that overloading << (and >>) is quite useful for user-defined types and makes for easier syntax further down the line.

I hope that helps.
Last edited on
I did remove the post, for some reason didn't think it was appropriate to ask you to explain the concept. Last time I asked a similar question on stackoverflow I was bombarded with people saying I should study more. Nice to see that isn't the case here.

It's probably not precisely what you want (you probably need more integers), but you should get the gist.

Thanks for explaining the code, its much clearer now. I've made some tweaks here and there for it to better accommodate my systems needs.

However, there is another issue that I am facing, anything I write into the text replaces the previously written text. I intended on putting a delete and edit function in the near future and want to be able to add more then one entry into the text files. Any suggestions? I'd rather not change the logic of the code you've written too much, I like the fact that its simple, straight forward and easy to read.
For one run of the program, the THING structures should be written sequentially to file (see my example of the output) and there will be no overwriting.

If you rerun the program, then you can open the file for append (i.e. add to the end instead: the default is to overwrite). See
http://www.cplusplus.com/reference/fstream/ofstream/open/

You may want to write an overloaded >> operator to match the output operator if you will be using the data file repeatedly. (Note that the THING would need to be passed as a reference, &, in that instance).
I've decided against writing an overload function all I had to do was add this based of the link you shared.

ofstream out("SelangorStations.txt", ofstream::out | ofstream::app);

The program seems to be running perfectly now.

Thanks for the help @lastchance I appreciate it.
Topic archived. No new replies allowed.