Apr 30, 2017 at 5:51pm UTC
Hello, my program does't seem to be working. It was supposed to write how many times the inserted name was used in the txt document. I think that the problem might be with the string inserted text. But the k returns as 0.Any help is appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
#include <fstream>
using namespace std;
struct Song{
string band;
string song;
double m;
double s;
};
void read (Song S[],int &n);
int main()
{
int k = 0;
int n;
Song S[100];
string name;
cout << "Enter bands name: " << endl;
getline(cin,name);
read(S,n);
for (int i =1;i<=n;i++)
{
if (name == S[i].band)
{
k++;
}
}
cout << "Number of " << name << " songs: " << k << endl;
return 0;
}
//-------
void read (Song S[],int &n)
{
ifstream fd ("d.txt" );
fd >> n;
for (int i = 1;i<=n;i++)
{
getline(fd,S[i].band,'-' );
getline(fd,S[i].song,',' );
fd >> S[i].m >> S[i].s;
}
}
Last edited on Apr 30, 2017 at 6:26pm UTC
Apr 30, 2017 at 5:53pm UTC
Im very confused.
read(D,n) // What is "D"? Your array is called "S".
1 2 3 4
if (name == D[i].band) // Same here. Your array was created as Song S[]. Not Song D[]
{
k++;
}
This is also an incorrect for-loop if you want to loop through the entire array -
for (int i = 1;i<=n;i++)
Array indexes start at 0. So if you have an array of 100. they would be 0-99.
1 2 3 4
for (int i = 0; i < 100; i++)
{
// code here
}
Last edited on Apr 30, 2017 at 5:57pm UTC
Apr 30, 2017 at 6:28pm UTC
sorry, i changed the names from my native language so left some unchanged.
im worried the most about this part:
string name;
getline(cin,name);
read(S,n);
for (int i =1;i<=n;i++)
{
if (name == S[i].band)
{
k++;
}
can the string be compared to an array?
Last edited on Apr 30, 2017 at 6:28pm UTC