-
If statment +text
I want to type in a text with the std::cin and then store it in a variable, like:
char text[20];
std::cin >> text;
Then comes the problem, I want to use the if statement and depending on whatever you've typed in launch a specific action, like:
if (text=="whatever") {std::cout << "this is some text";};
else if (text=="I am old") {std::cout << "No, you're young";};
else {std::cout << "Type in something else";};
But it doesn't work out!
Help me solve this!!!!!!!!!!!!
-
Try the function strcmp(). It compares C Style strings and gives out 0 if they are both the same
-
Code:
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main(void)
{
char text[20];
cin.getline(text, 20, '\n');
if(strcmp(text, "whatever"))
std::cout << "this is some text";
else if(strcmp(text, "I am old"))
std::cout << "No, you're young";
else
std::cout << "Type in something else";
return EXIT_SUCCESS;
}
-
that code won't work. strcmp returns 0 if true. therefore u have to type ! before every time u use it.
ex. if (!strcmp(text,"whatever")
{//do whatever}
-
Convert the array 'text' to a string, and then compare.
string answer;
ie. answer = text;