2017-04-15 146 views
1

我编写了一个进入文件并将txt文件的每一行复制到数组索引中的程序,然后将该文本行的该行放入另一个数组中按字符分隔线。我试图将字符数组中的第一个索引与“H”进行比较,但我无法做到这一点。如何将数组内的字符与另一个字符(如“H”)进行比较。如何将字符数组中的值与另一个字符进行比较

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, char* argv[]) { 
    char const* const fileName = argv[1]; 
    FILE* file = fopen(fileName, "r"); 
    int i = 0; 
    char line[256]; 
    char* str[256]; 
    while (fgets(line, sizeof(line), file)) { 
      str[i]=strdup(line); 
      strcpy(str[i],line); 
      i++; 
    } 
    char tmp[256]; 
    memcpy(tmp, str[0],strlen(str[0])+1); 
    if(strcmp(tmp[0],"H") == 0){ 
      printf("%s","is h"); 
    }else{ 
      printf("%s","not h"); 
    } 
    fclose(file); 
    return 0; 
} 
+0

我没试过你的代码,但'tmp'被正确初始化到正确的值,你可以就可以说'TMP [0] ==“H''。 H'被转换为字符“H”的ASCII值,所以只需将该值与'tmp [0]'的ASCII值进行比较就足够了。 – SpencerD

回答

0

这不是很清楚你正在尝试做的,也许它会更容易让你使用C++文件/阵列/串原语。

下面是在C++相当于:

#include <fstream> 
#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

int main(int argc, char* argv[]) 
{ 
    ifstream fl(argv[1]); // create file stream 
    string s; 
    vector<string> lines; 
    while (getline(fl, s)) // while getline from input file stream succeeds 
     lines.push_back(s); // add each read line to vector of strings 
    string tmp = lines[0]; // first line 
    if (tmp[0] == 'H') // compare first character of string `tmp` 
     cout << "is h" << endl; 
    else 
     cout << "not h" << endl; 
} 

在你的代码正在传递一个char到strcmp:strcmp(tmp[0],"H")这不会被C++编译器编译。 strcmp需要两个字符串作为输入并对它们进行比较。

比较个别字符:if (tmp[0] == 'H') { ... }

如果您想比较tmp是否等于"H"字符串:if (0 == strcmp(tmp, "H") { ... }

+0

非常感谢你提供了这样一个详尽的答案,并深入探讨了为什么它给了我这个特定的错误。将其更改为if(tmp [0] =='H')确实解决了我的问题。 – Osais101

1

您应该将数组[索引]与char进行比较。注意:字符用单引号表示。双引号用于字符串。

例如,

if(array[index] == 'H') 
    code goes here... 
+0

谢谢,这实际上解决了我无法比较它们的问题。 – Osais101

相关问题