Hello! :)

I'm having a problem while comparing one character from a string with a ... string.

This is a part of a pretty complex loop (or, it's complex for me, since I'm new to C++ and programming), but the case is that I need to compare the value of a given i index of a string to a string. For example:

#include <iostream>
#include <string>

using namespace std;

int main()
	string str = "Arne Kristoffer rules";
	for(int x = 0; x != str.length(); x++)
		if (str[x] == "a")
			cout << str[x];
	return 0;

Well, this is just a silly example program, but I hope you see whats wrong (because I don't...)

Thanks! :)

(PS: If you don't understand my english or if I have done something against the forum rules, please send me a PM, so it won't happen again.)

Recommended Answers

All 3 Replies

Very simple mistake: if (str[x] == "a") should be: if (str[x] == 'a') You are comparing each character from a string with another character, so you need single quotes instead of double

if I have done something against the forum rules

Actually, you are one of the few people who get the Code-tags right in their first post, so : bravo!

line 11: you don't do it like that. use single quotes to compare characters if (str[x] == 'a') [edit]^^^ like he said[/edit]

Thank you very much, this solved the problem! :)

Have a nice weekend!

Arne Kristoffer

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.