SRL Archive - C/C++ Help and Tutorials

What is wrong here? (if- statement)


marpis

2008-12-03 15:22:35

What is wrong with the if- statement? Even if i wrote laura as FirstName, it doesn't print "I knew its you". Google didn't help me at all

#include <cstdlib>
#include <iostream>
#include <fstream>


using namespace std;

int main(int argc, char *argv[])
{
char FirstName[30], LastName[30];
int Age;
char FileName[20];
cout << "First name:";
cin >> FirstName;
if (FirstName == "laura")
{
cout << "I knew it's you!" << endl;
}

cout << "Surname: ";
cin >> LastName;
cout << "Age:";
cin >> Age;

cout << "\nFilename (remember .txt) ";
cin >> FileName;
ofstream Students(FileName, ios::out);
Students << FirstName << "\n" << LastName << "\n" << Age;

cout << "\n\n";
return 0;

system("PAUSE");
return EXIT_SUCCESS;
}

Yakman

2008-12-03 16:48:28

replace this

if (FirstName == "laura")

with this

if (strcmp(FirstName, "laura") == 0)

and add


#include <cstring>

to the top


of course there is a c++ way of doing it, I've shown you the c way.


that happens because you are not checking if the buffer contains the characters "laura", you are checking if the two buffers are stored in the same location. which always results false.

this is because c++ inherits string literals from c
when you write "laura", that is a pointer to a character, which is a very c-like way to handle strings.

there is the more c++-like class called 'string',


it overrides the + operator, so you can do

string str;
str = str + "hello there";
str = "hi" + str;

but if you try to do


"hello" + " there"

it wont work, because those are pointers to chars, not c++ strings.



c++ has some of these quite odd features which come from the fact that it inherits from c.
if you are just learning c++, i would recommend you learn c first, then when you know it well enough, go to c++ and you'll understand why the odd features happen.

marpis

2008-12-04 00:32:51

Working now, thanks alot :)
I give c++ a shot and if it seems way too hard for me i start learning c.

boberman

2008-12-05 20:26:02

From: marpis
Working now, thanks alot :)
I give c++ a shot and if it seems way too hard for me i start learning c.


lol, you are already using c++. iostream, and fstream, are both c++ libraries. C++ can for the most part be used exactly like c. (most c code you can run through a c++ and get an executable). The difference is that C++ gives the ability for someone to use OOP. Thats the main feature of C++.