comparing char array to char always returns true

Hello
I've made a code to check whether or not a save file has been created correctly, but for some reason it always returns this line: readdata[qa]=='1' as true. in which qa is the counter I use in a for loop and readdata is a character array consisting of 50 characters that are either 0, 1 or 2.
this is the entire code:
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	fstream control;
	control.open("saveFile.txt", fstream::in);
	int oneCounter = 0;
	int otherCounter = 0;
	char * readdata;
	readdata = new char[50];
	control.read(readdata, 50);
	int readchars = control.gcount();
	if (readchars != 50)
		return 0;
	else
	{
		for (int qa = 0; qa < readchars; qa++)
		{
			if ((readdata[qa]=='0') ||(readdata[qa]=='2'))
			{
				otherCounter++;
			}
				
			if ((readdata[qa]=='1'));
			{
				oneCounter++;
				if (oneCounter > 1)
					return 0;
			}
		}
		delete[] readdata;
		if (oneCounter == 1 && otherCounter == 49)
			return 0;
	}
}

at first is also went wrong at line 22 and also returned that as true, but then I added brackets and it worked.
any help on this?
Can you post a sample of your saveFile.txt so that we can test the code?
EDIT - I found it!

Remove the semicolon from if ((readdata[qa]=='1')); and it should be ok.
1
2
3
4
5
6
if ((readdata[qa]=='1')); //←Look here
{
    oneCounter++;
    if (oneCounter > 1)
        return 0;
}
It is equivalent to
1
2
3
4
5
6
7
8
if ((readdata[qa]=='1'))
   /*Do nothing*/;
{ //Useless brackets
    //Following will be executed unconditionally
    oneCounter++;
    if (oneCounter > 1)
        return 0;
}
Turn on compiler warnings. There is literally no compiler which wont warn about empty body of loop/conditional statement.
yes, thank you all, I just figgured out the same thing, but still thanks!
I love how fast people respond to things on this site!
(the savefile contains a 1 and then 49 0's if all is right)
Last edited on
Topic archived. No new replies allowed.