I want to create a struct containing a double and a vector of strings. I tried this
int main ()
{
struct List
{
double price;
vector<string> items;
};
List list;
ifstream infile ("Aap.txt");
double p;
infile>>p;
list.price=p;
cout<<list.price<<endl;
int i=0;
string name;
getline(infile,name);
while(infile)
{
list.items.push_back(name);
cout<<list.items[i]<<endl;
i++;
getline(infile,name);
}
infile.close();
if (!infile)
{
cout<<"File closed."<<endl;
}
return 0;
This is not filling my vector, because it is not by reference in the struct I suppose?
But when I define the vector in the struct as:
vector<string>& items;
I get an error saying:
error: structure `list' with uninitialized reference members.
How can I fix this?
Thank you for helping!
Your code works perfectly fine.
There's a little issue of the first read: if you have a newline character in your input file after the price value, that newline character will remain unread. In this situation the first call to getline will read an empty string, meaning that the first name in your items array will end up empty.
Related
I have a Movie class which has constructor takes 7 parameter like this;
Movie:: Movie(string ttle,string sts ,double prc,int yr,string gnr,Date rls,int id)
I would like to use dynamic memory for an movie array but it gives error and i could not find it
int main() {
int counter=0; // size of array
Movie *moviearray;
moviearray= new Movie[counter];
ifstream filein("DVD_list.txt");
for (string line; getline(filein, line); )
{
counter++;
vector<string> v;
split(line, '\t', v); // v is an vector and puts string words that has splitted based on tab
moviearray[counter] =(v[0],v[1] ,stod(v[2]),stoi(v[3]),v[4],Date(v[5]),stoi(v[6])); // ERROR
How can I create an movie object in that array?
This:
int counter=0; // size of array
moviearray= new Movie[counter];
Does not make sense. You are allocating an array of zero objects. Later you use it. This is illegal.
Instead, try:
std::vector<Movie> movies;
Then in your loop:
movies.push_back(Movie(v[0],v[1] ,stod(v[2]),stoi(v[3]),v[4],v[5],stoi(v[6])));
In my program I am trying to take from the user lines of input actually names then storing them into a vector.
I wrote my own code but I got a runtime error telling me that "string subscript out of range".
This is my code
const int LEN = 100;
struct Case{
public:
int No_People;
vector<string> Names;
vector<string> Results;
void Set_Data(){
cin >> No_People;
int Size = No_People;
char Line[LEN];
for (int i = 0; i < Size; i++){
cin.getline(Line, LEN);
Names.push_back(Line);
}
}
}
Personally I would define a class to represent a line. Then you can use stream iterators to load the vector.
class Line
{
std::string line;
public:
// Operator to convert a line back to a std::string
operator std::string const&() const {return line;}
// Friend function to read a line from a stream.
friend std::istream& operator>>(std::istream& in, Line& data)
{
return std::getline(in, data.line);
}
};
int main()
{
int countOfPeople;
std::cin >> countOfPeople;
std::vector<std::string> lines;
std::copy_n((std::istream_iterator<Line>(std::cin)), countOfPeople,
std::back_insert_iterator(lines));
}
There's no need to use a char[] array, use std::string instead, especially given that you already are using it.
Note to OP: cin.getline() is this one:
std::istream::getline(char*, int)
The one you ned to use for std::string's is this one:
std::getline(istream&, string&)
struct Case{
public:
int Size;
vector<string> Names;
vector<string> Results;
void Set_Data(){
std::string temp;
cin >> Size; cin.ignore();
for (int i = 0; i < Size; i++){
std::getline(cin, temp);
Names.push_back(temp);
}
}
}
As far as compile errors go, always:
quote the exact error messgae
tell the line it happened at
show the code that contains the line and the relevant classes/methods
Most probably you are accessing the string using subscript which is out of index. It will be easy to answer if you point at which line you are getting the error.
I have text file like this:
7
a
bkjb
c
dea
hash_table is an array such that line no.-2=index of hash_table array that is every line corresponds to an element in array. The element may be empty line or character like "a\n" which will like this in text file:
a
//empty line
First number is used to decide the size an array hash_table.
THe << operator is not treating empty line or '\n' char as string and hence not adding into array.
I tried this but no use . Here is my try:
ifstream codes ("d:\\test3.txt"); //my text file
void create_table(int size, string hash_table[]) //creating array
{ string a;
for(int i=0;i<size;i=i+1)
{
codes>>a;
char c=codes.get();
if(codes.peek()=='\n')
{char b=codes.peek();
a=a+string(1,b);
}
hash_table[i]=a;
a.clear();
}
}
void print(int size, string hash_table[])
{
for(int i=0;i<size;i=i+1)
{if(!hash_table[i].empty())
{cout<<"hash_table["<<i<<"]="<<hash_table[i]<<endl;}
}
}
int main()
{
int size;
codes>>size;
string hash_table[size];
create_table(size, hash_table);
print(size, hash_table);
}
NOTE: there can be any no. of empty lines with random sequence.
Use std::getline() instead of std::ifstream::operator >>(). The >> operator will skip over whitespace, including newlines.
std::string line;
while (std::getline(codes, line)) {
//...do something with line
}
I wrote a function to read a text file, create an array from the integer values in the file and return the reference of that array to main function. The code I wrote(in VS2010):
//main.cpp
void main(){
int T_FileX1[1000];
int *ptr=readFile("x1.txt");
for(int counter=0; counter<1000; counter++)
cout<<*(ptr+counter)<<endl;
}
and the function is:
//mylib.h
int* readFile(string fileName){
int index=0;
ifstream indata;
int num;
int T[1000];
indata.open("fileName");
if(!indata){
cerr<<"Error: file could not be opened"<<endl;
exit(1);
}
indata>>num;
while ( !indata.eof() ) { // keep reading until end-of-file
T[index]=num;
indata >> num; // sets EOF flag if no value found
index++;
}
indata.close();
int *pointer;
pointer=&T[0];
return pointer;
}
the data in the file contains positive numbers like
5160
11295
472
5385
7140
When I write each value in "readFile(string)" function, it writes true. But when I wrote it to screen as U wrote in "main" function, it gives values strangely:
0
2180860
1417566215
2180868
-125634075
2180952
1417567254
1418194248
32
2180736
irrelevant to my data. I have 1000 numbers in my file and I guess it raves these irrelevant values after a part of true writing. E.g. it writes first 500 values true, and then it writes irrelevant values to my data. Where is my fault?
int T[1000];
...
pointer=&T[0];
you are returning a pointer to a local stack variable which is going to get destructed.
I think what you want to do is to pass in the array T_FileX1 that you have defined to the function and use that directly to read the data into.
You return a pointer to the first element of an array which is allocated on the stack and gets destroyed after your function returns. Try using a vector instead:
vector<int> readFile(string fileName) {
ifstream indata;
int num;
vector<int> T;
indata.open("fileName");
if(!indata){
cerr<<"Error: file could not be opened"<<endl;
exit(1);
}
indata>>num;
while ( !indata.eof() ) { // keep reading until end-of-file
T.push_back(num);
indata >> num; // sets EOF flag if no value found
}
indata.close();
return T;
}
This is a case of undefined behavior. You return a pointer to a local variable, when the function returns the part of the stack used by the function is no longer valid.
Pass the array as an argument to the function instead.
I am trying to pull characters from a specific column (in this case, 0) of a text file, and load them into a vector. The code seems to work ok, until it reaches the end, when I get a "string subscript out of range" error, and I do not know how to fix this. Does anyone know what I can do? Here is the relevant code.
class DTree
{
private:
fstream newList;
vector<string> classes;
public:
DTree();
~DTree();
void loadAttributes();
};
void DTree::loadAttributes()
{
string line = "";
newList.open("newList.txt");
string attribute = "";
while(newList.good())
{
getline(newList, line);
attribute = line[0];
classes.push_back(attribute);
}
}
Please try 'while(getline(newList, line)'
Refer here
You can also try something like
ifstream ifs("filename",ios::in);
string temp;
getline(ifs,temp)// Called as prime read
while(ifs)
{
//Do the operations
// ....
temp.clear();
getline(ifs,temp);
}
ifs.clear();
ifs.close();
This works for almost all kinds of files.You can replace getline(ifs,temp) by get() function or by >> operator based on your requirements.