C++ Compare char array with string

后端 未结 6 1763
悲哀的现实
悲哀的现实 2020-11-29 05:06

I\'m trying to compare a character array against a string like so:

const char *var1 = \" \";
var1 = getenv(\"myEnvVar\");

if(var1 == \"dev\")
{
   // do stu         


        
6条回答
  •  无人及你
    2020-11-29 05:36

    your thinking about this program below

    #include 
    #include 
    
    int main ()
    {
    char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
    int n;
    puts ("Looking for R2 astromech droids...");
    for (n=0 ; n<3 ; n++)
    if (strncmp (str[n],"R2xx",2) == 0)
    {
      printf ("found %s\n",str[n]);
    }
    return 0;
    }
    //outputs:
    //
    //Looking for R2 astromech droids...
    //found R2D2
    //found R2A6
    

    when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below

    #include 
    #include
    #include 
    #include 
    using namespace std;
    
    int main()
    {
    int Students=2;
    int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
    int Grades[Students][Projects];
    
    for(int j=0; j<=Projects-1; j++){
      for(int i=0; i<=Students; i++) {
     cout <<"Please give grade of student "<< j <<"in project "<< i  <<  ":";
      cin >> Grades[j][i];
    
      }
      Sum2 = Sum2 + Grades[i][j];
         Avg2 = Sum2/Students;
    }
    SumT2 = SumT2 + Avg2;
    AvgT2 = SumT2/Projects;
    cout << "avg is  : " << AvgT2 << " and sum : " << SumT2 << ":";
    return 0;
    }
    

    change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    int main()
    {
    char name[100];
    //string userInput[26];
    int i=0, n=0, m=0;
    cout<<"your name? ";
    cin>>name;
    cout<<"Hello "<

提交回复
热议问题