strcmp function error

Hello,

i am comparing 2 strings using strcmp function. the first argument is a string vector with 10 elements and the second a string. the if(expression) is working properly, however when i am trying to save the table[1] string to the next string it is not working, which means that the next string is empty.

1
2
3
4
5
6
string surname; // we assume that the surnmame and table[0] are the same strings.
string next ;

if( strcmp(table[0].c_str(), surname.c_str() ) == 0 )
    next = table[1] ;
cout << next ; // the next string is empty 



any help please.
I did this and it worked fine. Did I misunderstand the question? The vector only has 2 elements, but it's enough to see if it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>
#include <cstring>

using namespace std;

int main()
{
    vector<string> table;
    table.push_back("Smith");
    table.push_back("Jones");
    string surname="Smith"; // we assume that the surnmame and table[0] are the same strings.
    string next;

    if( !strcmp(table[0].c_str(), surname.c_str() )  )
        next = table[1] ;
    cout << next ; // the next string is empty

    return 0;
}

The output in this case is:
Jones
Also note the change I made in line 16. It is not important to the code, but it seems easier to read to me.
Last edited on
Care to explain why you are using strcmp? You should be writing if(table[0]==surname)
Aside from that, you're probably making assumptions that are not true (table[0] being equal to surname or table[1] being not empty). Use the debugger to step through your program.
Topic archived. No new replies allowed.