Help with if statement

Hello again,

I've been struggling with this code for a while. I need help solving my if statement issue. The problem is that I need my if statement to print out one message if it's equal to a string value and do nothing if it doesn't match. I don't think I can use a strcmp because I only have one string to compare. I am new and I can't seem to get a general sense on the topic from any forums. Could we please keep it as beginner as possible? I want to learn, not just be told the answers. Does anyone know if C++ doesn't read strings in an if statement?

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
47
48
49
50
51
52
 4  #include <iostream>
  5 #include <cctype>
  6 #include <cstring>
  7 
  8 using namespace std;
  9 
 10 const int  NAME = 21;
 11 const int  MAJOR = 45;
 12 
 13 
 14 int main()
 15 {
 16     char person [NAME]; // variables store names of users
 17     char declare_m [MAJOR];
 18 
 19 
 20     cout << "Enter name: " << endl; //gets user names and converts to upper
 21     cin.get(person, NAME, '\n');
 22     cin.ignore(100, '\n');
 23     person[0] = toupper(person[0]);
 24 
 25     int len1 = strlen(person);// capitalizes every word after a statement
 26     for (int i = 1; i < len1; ++i) //starts index 1
 27       {
 28        if(person[i] == ' ')
 29           person[i+1] = toupper(person[i+1]);
 30       }
 31     cout << "Hello " << person << endl;
 32 //    cout << "Length of word is: " << len1 << endl;
 33 
 34     cout << "What's your major? " << endl; // get user major
 35     cin.get (declare_m, MAJOR,'\n');
 36     declare_m[0] = toupper(declare_m[0]);
 37     cin.ignore(100,'\n');
 38 
 39     int len2 = strlen(declare_m); //capitalize major even strings
 40     for (int i = 1; i < len2; ++i)
 41     {
 42         if( declare_m[i]  == ' ')
 43            declare_m[i+1] = toupper(declare_m[i+1]);
 44     }
 45 
 46 
 47    if ( "Computer" == declare_m )
 48         cout << "Your major is " << declare_m << "Fellow" << endl;
 49    else 
 50        // cout << "Your major is: " << declare_m << "fellow nerd!!!" << endl;
 51      cout << "didn't work" << endl;
 52 
 53      return 0;
 54 }
Add the header #include <string>

This is not the same as #include <cstring> .
Last edited on
Merely adding header for std::string does not solve the problem.

The declare_m is a char array. "Computer" is a (const) char array. The == does not compare such strings. You need a function.
See: http://www.cplusplus.com/reference/cstring/strcmp/


Users of C++ should avoid unnecessary arrays. That is where the std::string comes in. It is more flexible than plain char array.
Topic archived. No new replies allowed.