if-else condition problem using in a loop

I've written a solution for the UVa problem NO#12250.
My logic is ok I think but the loop terminates in first input.

Here is the code..
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
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

int main ()
{
    string s;

    for(int i=1; ;i++)
    {
        scanf("%s",s.c_str());

        if(s.compare("#"))
            break;
        else if(s.compare("HELLO"))
            printf("ENGLISH\n");
        else if(s.compare("HOLA"))
            printf("SPANISH\n");
        else if(s.compare("HALLO"))
            printf("GERMAN\n");
        else if(s.compare("BONJOUR"))
            printf("FRENCH\n");
        else if(s.compare("CIAO"))
            printf("ITALIAN\n");
        else if(s.compare("ZDRAVSTVUJTE"))
            printf("RUSSIAN\n");
        else
            printf("UNKNOWN\n");
    }

    return 0;
}



Why?
Probably because you're trying to use scanf() with a std::string.

First figure out if you want to write a C or C++ program then use the proper constructs for the language you choose. If you decide to use C++ stick with C++ streams instead of Cstdio functions. If you decide to use C then stick with character strings instead of C++ strings.

Second you need to realize that c_str() returns a const C-string that can't be modified, which is what you're trying to do with scanf().


scanf("%s",s.c_str()); Invalid. You should not modify data by pointer returned by c_str(). Actually this is example of how dangerous scanf is: any other sane function would give you an error: type mismatch.

s.compare("HELLO") and others: compare returns 0 (false) when strings are equal. It mimics strcmp in that regard. So if you enter anything not equal to "#", condition on line 15 will evaluate to true and break statement executes.

s == "Hello" would be enough
I used cin and cout but still no working.
Last edited on

In addition to what @jlb said, std::compare returns 0 if the comparison matches your test, therefore line 15 will return something other that 0 if it doesn't match #. See http://www.cplusplus.com/reference/string/string/compare/ especially the section on return values.

If you think of how a Boolean is stored in memory, 0 is false, true is 1 (but anything other than 0 is considered true) so that line will always execute the break statement.
Thank you all.
Your welcome :)
Topic archived. No new replies allowed.