2017-04-15 142 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

相關問題