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
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
usingnamespace 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.
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.