I just want to take a moment to thank everyone for being so helpful. I've only asked one question (this being my second) but I got fast and accurate help with my first issue! I really like the community here, thanks for making me feel so welcome!
Now to my question... I recently ran into problems with arrays. I have since been able to get my program working and can now open the file and input a name and it will be added to the file and then the array (files contents) will be outputs on the console for the user.
My problem is:
Can I add something to check the the names in the array for a duplicate name after the user inputs the name she/he wants to add, then tell the user whether the name is in the file or not?
I've tried to do this myself and failed miserably. I think my newness and my sloppy code are causing problems. Here is my current program (the one I described above:
- Read the name you want into a string
- Copy the contents of the file into an array (you already did this)
- Set a boolean value called found to false
- Use a while loop to iterate over the contents of the array with the condition being while number of names read is less than 1000 and found = false. If the name is found, set found to true
- After the loop is finished, you check if found is true, and if it is you know that the name the user entered is in the array, otherwise it isn't
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <conio.h>
usingnamespace std;
int i;
int count = 0;
char n;
int main()
{
string line;
string harray[1000]; //name of array
ifstream infile("names.txt"); // storage
char n;
cout << "Please enter a first name in lowercase letters: ";
cin >> n;
bool found = false;
while (i < 1000 && !found)
{
if (found = true)
{
cout << "We found this name in the file" << endl;
}
//below stores words in the array
int count = 0;
while ((infile >> line) && (count < 1000))
{
harray[count++] = line;
}
cout << "Array contents:\n";
for (int i = 0; i < count; i++)
{
cout << harray[i] << "(" << i << ")" << endl;
}
cout << "Press return to continue\n";
char junk;
cin >> junk;
return(0);
}
I am far too new... I apologize but this just isn't working.
Your squiggly brackets don't seem to match up.
I use the code::blocks ide and when the the cursor is on a squiggly bracket the nearest matching one is also highlighted.
The other error is in
if (found = error)
= is an assignment operator in c++
if(found == error)
is probably what you wanted.
Also you use too many spaces and they lose their ability to block code in a useful way.
You both have been amazing! Thanks to the two of you, my program is working like a charm!!! I can't believe missing a "=" messed things up and had be baffled for so long!