Strings

I need to make a program that asks for a name, and until the user enters Bernice it keeps asking for name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main()
  5 {
  6   int name;
  7   string Bernice;
  8   string Bernice= "Bernice";
  9 
 10   cout << "Please enter a name" << endl;
 11   cin>> name;
 12 
 13   while (name!=Bernice)
 14   {
 15     cout << "Please enter another name" << endl;
 16     cin >> name;
 17   }
 18 
 19   cout << "Correct name, You entered Bernice" << endl;
 20 
 21 }
 22 


This is what I have so far. I'm not sure if all my variables are correct or if I'm correctly defining the string Bernice.
What makes you think the program is not already working?
First thing I see off the bat is that you're double declaring Bernice -- you only need to type string once, when you're initially declaring the variable. After that you can just use it normally. i.e.
1
2
string Bernice;
Bernice = "Bernice";


Second thing is you're accepting input into an integer and then comparing it to a string which makes no sense. Fix those things and you might be able to get it working.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 1 #include<iostream>
  2 using namespace std;
  3 
  4 int main()
  5 {
  6   int name;  // This needs to be a string
  7   string Bernice;  // You do not need this, the next line covers the whole declaration
  8   string Bernice= "Bernice";
  9 
 10   cout << "Please enter a name" << endl;
 11   cin>> name;
 12 
 13   while (name!=Bernice)
 14   {
 15     cout << "Please enter another name" << endl;
 16     cin >> name;
 17   }
 18 
 19   cout << "Correct name, You entered Bernice" << endl;
 20 
 21 }
 22 
You may not define a name twice as you did with Bernice;. The compiler shall issue an error. Also variable name shall be defined as std::string.

As for your assignment then it is very simple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

using namespace std;
 
int main()
{
   const char *Bernice = "Bernice";
   string name;

   cout << "Please enter a name" << endl;
   cin>> name;

   while ( name != Bernice )
   {
      cout << "Please enter another name" << endl;
      cin >> name;
   }
 
   cout << "Correct name, You entered " << Bernice << endl;
 
}


Last edited on
Topic archived. No new replies allowed.