Need help with this assignment.

Hi, I am going to make a function that searches for a word or some letters in a list of names and presents every name that includes those words or letters.I read string::find article at this site, however when I tried to make a simple program out of it I failed. This is what I came up with:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>
#include <string> 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  string n;
        for(int i = 0; i < 5; i++){
		cout << "Name: ";
		cout << n[i];
	}
  cout << "Write the name you want to 
  search for: ";
  string name;
  getline(cin, name);
  size_t found;
  found=n.find(name);
  if (found!=string::npos){
    cout << "The whole name is: " << found;
}
	return 0;
}
Last edited on
You're trying to print the first five characters of n, even though it is empty.

You probably want a vector of strings and instead of printing non-existent characters, you should read strings from the user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>
#include <string> 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	string n[20];
	cout << "Write: ";
	for(int i = 0; i < 5; i++){
		getline(cin, n[i]);
		cin.ignore(1000, '\n');
	cout << "Write the name you want to search for:";
	string name;
	getline(cin, name);
	size_t found;
	found=n[i].find(name);
  if (found!=string::npos){
    cout << "The whole name is: " << found; 
	}
	}
	return 0;
}


This is the new code I came up with, however I noticed "found" is the position of the name I searched for and not the name itself, quite obvious when I think about it but how do I return the name itself? I noticed many errors, like right now it only takes 1 name (not the surname) and I separate the names with spaces and also the whole found thingy only finds the position (as told).

I don't know whether you can help me any further or if this is just me being stupid and needing to restart fresh in the morning and try to come up with something.
Topic archived. No new replies allowed.