if (ans == "begin")
you can use strcmp from string.h library
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
you should have edited your first post instead of creating a duplicate
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
You place a cout statement to check for a value and then as for input to change that value again before using it. What is the reason of your call to getline ?
L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
if (ans == "begin")
you can use strcmp from string.h library
ans is an std::string object, the == operator is properly overloaded, so this test is correct. The problem, I suspect, is that the code requests input twice and the OP has incorrect expectations.Any help would be greatly appreciated, thanks!
No offense, but your code is awful. goto shouldn't be used where a simple loop works, and you don't have any conditions for breaking out of the loop. Notice that in both the "begin" and not "begin" conditions, the behavior is the same: print a message, call _getch(), and restart at the beginning. This can easily be accomplished with a loop:
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string ans;
while (true) {
cout << "Input: ";
// Otherwise the loop is infinite
if (!getline(cin, ans))
break;
if (ans == "begin")
cout << "You typed 'begin'\n";
else
cout << "You didn't type 'begin'\n";
_getch();
}
}
And assuming the "begin" case is for restarting at the beginning and all other cases terminate the loop, you can now add a break or set a flag for the loop's condition in the else clause:
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool done = false;
string ans;
while (!done) {
cout << "Input: ";
// Otherwise the loop is infinite
if (!getline(cin, ans))
break;
if (ans == "begin")
cout << "You typed 'begin'\n";
else {
cout << "You didn't type 'begin'\n";
done = true;
}
_getch();
}
cout << "All done\n";
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401