How to initialize a vector of structs with user data

I would want to initialize the following struct with user data using a vector of strings as below, how do i do it because it wouldnt run ?

code starts here:


[<i>]

#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>

struct LandStruct { // declaring a struct

string Surname;
string OtherNames;
string LandNum;
string KraPin;
string OwnerIdCard

};




int main()
{
std::vector <LandStruct> myStructs; //declaring a struct

LanStruct obj;

cout<<"Welcome to the new lands management information system\n\n";

cout<<"Enter Surname of land holder"<<endl;
myStructs.pushback (obj [0].Surname);

cout<<"Enter Other names of land holder"<<endl;
myStructs.pushback (obj [0].OtherNames);


//and all the other struct variables


system ("pause");

return 0;

}

[<\i>]

Last edited on
Write a function:

1
2
3
4
5
6
7
8
9
10
11
LandStruct ask_user_for_LandStruct()
{
  LandStruct result;

  cout << "Enter Surname of land holder: ";
  getline( result.Surname );

  ...

  return result;
}

Now you can use the function.

 
myStructs.push_back( ask_user_for_LandStruct() );

Hope this helps.
Thanks Duoas.

If i write this user data to text file using fstream, how can i search for some strings from the text file and display them if found in the text file e.g.



istream & search_string (std::istream& look_up)

{
fstream display;

display.open ("LandsFile.txt");

if (display !eof ());

for (size_t i=0; i<display.size(); i++);

if (look_up =="string_entered_by_user_to_search");

cout<<"The string"<<look_up<<"has been found with the following details:\n":

//here, a record should be displayed including other details that were stored with it in the text file e.g. if, it is the first name that has been searched, the rest of corresponding details like Othernames, KraPin, LandNum, etc.

return look_up;

}

int main () {

string look_up;
cout<<"Enter the first name of the holder to search from the register."<<endl;

getline (cin, look_up);

search_string (look_up);

}

Last edited on
You'll have to iterate through the vector (use a for loop) and check to see if the desired field has the substring the user is looking for.

You may also want to do a "case-insensitive" compare. Here's a function that may help:

1
2
3
#include <cctype>
#include <string>
...
1
2
3
4
5
6
std::string tolower( const std::string& s )
{
  std::string result{ s };
  for (char& c : result) c = std::tolower( c );
  return result;
}
1
2
// check if userinput is a substring of one of the Surnames in myStruts
if (tolower( myStructs[n].Surname ).find( tolower( userinput ) ) != std::string::npos) ...

Hope this helps.
Topic archived. No new replies allowed.