Menu

Problem using strcmp

Pramod
2008-04-15
2012-09-26
  • Pramod

    Pramod - 2008-04-15

    Hi,

    I'm new to programming in c++ and I've encountered a problem while trying to use the strcmp function. I use Dev c++ version 4.9.9.2. The program is a very simple one, trying to copy lines from one file to another till the occurence of a specific sentence. When trying to compile, it doesnt seem to like the strcmp function even though I've included

    include <string>. The program and compile log are shown below

    include <iostream>

    include <string>

    include <fstream>

    include <stdlib.h>

    using namespace std;
    int main()
    {

    string s=&quot;this sentence&quot;,t;
    
    ifstream fin;
    ofstream fout;
    
    fin.open(&quot;job-1.dat&quot;);
    if(fin.fail())cout&lt;&lt;&quot;opening failed&quot;;
    else cout&lt;&lt;&quot;opening successful&quot;;
    fout.open(&quot;copy.txt&quot;);
    
    do
    {
     getline(fin,t);
      fout&lt;&lt;t&lt;&lt;endl;
    
    }while(strcmp(t,s)!=0);
    

    fin.close();
    fout.close();
    system("pause");

    }

    The compile log is as follows:

    Compiler: Default compiler
    Executing g++.exe...
    g++.exe "C:\Dev-Cpp\trials\Untitled3.cpp" -o "C:\Dev-Cpp\trials\Untitled3.exe" -I"C:\Dev-Cpp\lib\gcc\mingw32\3.4.2\include" -I"C:\Dev-Cpp\include\c++\3.4.2\backward" -I"C:\Dev-Cpp\include\c++\3.4.2\mingw32" -I"C:\Dev-Cpp\include\c++\3.4.2" -I"C:\Dev-Cpp\include" -L"C:\Dev-Cpp\lib"
    C:\Dev-Cpp\trials\Untitled3.cpp: In function int main()': C:\Dev-Cpp\trials\Untitled3.cpp:26: error: no matching function for call tostrcmp(std::string&, std::string&)'
    C:/Dev-Cpp/include/string.h:43: note: candidates are: int strcmp(const char, const char)

    Execution terminated

    Any idea what I'm doing wrong ? This could be a total amateur mistake. Thanks a ton in advance.

    Cheers
    Pramod

     
    • Somelauw

      Somelauw - 2008-04-15

      strcmp() is for comparing char arrays. For cstring's you could just use the == operator like on integers, floats, etc.

       
    • BiT

      BiT - 2008-04-15

      C:\Dev-Cpp\trials\Untitled3.cpp:26: error: no matching function for call to `strcmp(std::string&, std::string&)'

      C:/Dev-Cpp/include/string.h:43: note: candidates are: int strcmp(const char, const char)

      two lines above are what you need to look at.
      They point out that first "no matching function for call to `strcmp(std::string&, std::string&)"
      and that the valid "candidates are: int strcmp(const char, const char)"

      Use the function "c_str()" to convert your strings to character arrays.

      strcmp(t.c_str(),s.c_str())

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.