Help Why doesnt this work?

When I type in a name nothing happens?

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
  #include <iostream>
#include <string>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;



std::string x;

int main() {
	
	cout << "What is your full name?\n";
	cin >> x;
	if(x=="Fred")
	{
		cout << "Computer says - You suck.\n";
	}
	else
	if(x == "Joe")
	{
	cout << " Computer says - You are the greatest!\n";
	
	
}
	return 0;
}
The code is fine, assuming you typed in Fred or Joe.

Notice the comment at the top.
run this program using the console pauser or add your own getch, system("pause") or input loop

You should run it through cmd (assuming Windows since you wouldn't have this problem on Linux in the first place).
Best solution is to have your IDE pause the console after execution so that you don't have to. All major IDEs like Code Blocks, Visual Studio, Eclipse, should have this option.

The problem is that your output happens so fast and program closes as soon as its calculations are done, so you have no time to see the output.

see http://www.cplusplus.com/forum/beginner/1988/ Duoas's explanation is great
@below Nevermind then.
Last edited on
closed account (E0p9LyTq)
You are only checking for two names, "Fred" and "Joe." If you enter anything else, even "fred" or "joe," both if statements are false.
NVM I got it I for some reason had a space in the names I was using so I guess the compiler cant handle that? How do I make it so lets say I type instead

if(x=="Fred Ford")
{
cout << "


If I type Fred Ford nothing happens
You need to use getline, the >> operator for cin is delimited by spaces and won't work - Only the first word will be stored in the strong.

See the example at: http://www.cplusplus.com/reference/string/string/getline/?kw=getline

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// extract to string
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin, name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

Last edited on
Thanks alot, and yea I saw the rant with duoas but I dont plan on doing anything publicly with my programs, I just like writing em for my own use. But W/e thank you for the help.
closed account (E0p9LyTq)
The reason why "Fred Ford" doesn't work is because you are using cin >> to get your name. cin "sees" the space in "Fred Ford" and retrieves only "Fred". Does "Fred" == "Fred Ford"? Nope.

If you want to properly retrieve "Fred Ford" with C++ strings you can use:

std::getline(std::cin, x);
Topic archived. No new replies allowed.