How to array string and int from text file

text file:
eric 1234e 110 3
minwei 1234m 540 3

the problem is
1>startmenu.cpp(471): error C2040: 'id' : 'std::string [100]' differs in levels of indirection from 'std::string'
1>startmenu.cpp(471): error C2040: 'pw' : 'std::string [100]' differs in levels of indirection from 'std::string'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 const int SIZE=100;	//save all data
	int tscore [SIZE], uunlocked[SIZE];
	string id[SIZE], pw[SIZE];
	int l=0;
	fp.open("membership.txt");
	if (!fp) cout<< "Unable to open file"<<endl;
	else
	{
		while(!fp.eof())
		{
			fp>>id[SIZE]>>pw[SIZE]>>tscore[SIZE]>>uunlocked[SIZE];
			l++;
		}
	}
	//update lines
	ofstream fp1;// CLear data
	fp1.open("membership.txt");

	fp.open("membership.txt");// Store data and new edited line
	for(int k=0;k>l;k++)
	fp << uid << " " << upw << " " << tscore << " " << uunlocked << " " << endl;
You shouldn't be using SIZE in your loop. The arrays are of size SIZE, so you'll actually index out of bounds.
Remember, we count from 0 in C++ (at least in this case), so using the size as the index is actually the size + 1 spot.
You should use l in your while loop instead.

You might want to just return if the file can't be opened:
1
2
3
4
5
if (!fp)
{
   cout << "Unable to open file" << endl;
   return -1; //Or return 0, but returning 0 indicates a program executed without problems
}

Or just enclose everything else in the else block, there is likely no point in trying to write anything to the file if you weren't able to open it.

I highly recommend initializing your variables. std::string will initialize itself, but integral types will not (char, int, etc), nor will float/double.

I also don't recommend looping over eof. However, I see most instructors teaching this.
eof doesn't actually get triggered until you've already reached the end of the file, which could result in unexpected results.
http://www.cplusplus.com/reference/ios/ios/eof/

This code works to read from the file:
1
2
3
4
5
6
7
8
9
  //While we are able to read in the id string
  //IF this operation completes successfully, it will be evaluated as true and the loop will execute
  //If this operation fails, execution will not enter the loop.
  while (in >> id[l])
  {
    in >> pw[l] >> tscore[l] >> uunlocked[l];
    std::cout << "id: " << id[l] << ", pw: " << pw[l] << ", tscore: " << tscore[l] << ", uunlocked: " << uunlocked[l] << std::endl;
    l++;
  }


And it produces the following output:
id: eric, pw: 1234e, tscore: 110, uunlocked: 3
id: minwei, pw: 1234m, tscore: 540, uunlocked: 3
Press any key to continue . . .


Perhaps that can help spin you in the right direction :D

Also, here's a page on the C2040 compiler error: https://msdn.microsoft.com/en-us/library/kb3dky0e.aspx
Last edited on
Thank you! i got it to work now :))
Topic archived. No new replies allowed.