I am trying to input a list of names into a array. The first name goes, but as soon as i increment to counter to install the next name into the next array position, the program crashes.
EXAMPLE:
Alvin
alfred
Alan
Augustus
Can someone please tell me what I am doing wrong?
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
string fileName,line;
ifstream infile;
cout<<"Enter the file name and complete path: ";
cin>>fileName;
int count=0;
string *A;
A=new string[count+1];
infile.open(fileName.c_str());
while(!infile.eof())
{
getline(infile,line);
if(line[count]=='A'||line[count]=='a')
{
A[count]=line;
cout<<A[count]<<endl;
count++;///CAUSES AN ERROR
}
}
return 0;
}
Actually, what causes the error is this line: A[count]=line;
Why? Because your array has only one element (that's what it started with, you can't change it without an explicit statement along the lines of "THIS ARRAY'S LENGTH WILL CHANGE TO THE PRESENT VALUE OF count PLUS ONE"). I recommend that you ust a vector instead, which you can read up on here: http://cplusplus.com/reference/stl/vector/
Oh... another thing... if(line[count]=='A'||line[count]=='a')
What is this supposed to do? In that loop, it will evaluate (for each of your names)
True
False
True
False
Is this what you wanted?
I am going through a long list of names and looking at the first letter of each name in order to get alphabetical arrays. I have never used a vector before and I also thought a dynamic array would be good for this sort of thing. I did declare a dynamic array, did i not?
Indeed. It will not, however, change as count does. It will only change when you tell it to change, and (as I never use arrays this might be wrong) it might change to a completely different sector of memory, so you'll lose your data.
If that is what you wanted (in reference to what you listed as what you wanted), then... count increases per iteration. So you'll be reading the first character of line, then the second character of the new value of line, then the third... and so on.
I do not want to lose any of my data. One my loop determines that a certain name belongs in a certain array, I want to simply store the entire name and then move on the looking at other names. Can you please give a simple example of a vector instruction. I looked at the link you provided and I am seeing classes and other complicated terms which i am not yet familiar with.
Here are some basic things you can do with a vector:
1 2 3 4
vector<type> name;//Initialize a vector.
name[int];//Access one element of the vector.
name.push_back(data);//Insert data into the vector, lengthening it automatically, and as needed.
//The data must by of type type.
I have installed the missing header and got rid of the undeclared identifier issue. Now I have only one error and I don't understand it or know where how to resolve it.