2017-11-05 3 views
2

私は保存した文字列の数を知っている関数を使ってstdinから42の文字列を読み込むコードを書こうとしています。 は、ここで私は今のところ思い付いたものです:Cの関数を使って文字列の配列を操作する方法は?

#define rows 42 
#define chars 101 

void populate(int* citiesCount, char cities[][chars]); 

int main() 
{ 
    char cities[rows][chars]; //array of strings to store all lines of txt file 
    int citiesCount = 0; //how many lines there really are (may be less than 42) 

    populate(&citiesCount, cities); 

    //print all cities 
    printf("NUMBER OF CITIES: %d\n", citiesCount); 
    for(int i = 0; i < citiesCount; i++) 
    { 
     printf("CITY: %s\n", cities[i]); 
    } 
    printf("END\n"); 

    return 0; 
} 

void populate(int* citiesCount, char cities[][chars]) 
{ 
    char cntrl; 
    for(int i = 0; i < rows; i++) 
    { 
     printf("%d\n", *citiesCount); 
     scanf("%100[^\n]", &cities[*citiesCount++]); //read line of txt file and save it to array of strings 
     printf("%s\n", cities[i]); 
     cntrl = getchar(); //check, if I'm at end of file, if yes break loop 
     if(cntrl == EOF) 
      break; 
    } 
} 

コードは、それが動的なメモリ割り当てを使用するようにを禁じである。このプロジェクトでは次の文

gcc -std=c99 -Wall -Wextra -Werror proj1.c -o proj1 

によってコンパイルされます。

私はコードをコンパイルしようとすると、私は次のエラーを取得する:

"'%[^' expects argument of type 'char *', but argument 2 has type 'char (*)[101]'"

私はそれに対処するためにあらゆる可能な方法を試してみましたが、何ワット作品を見つけることができませんでした。

+1

'scanfのに役立つはずscanf関数を使用しての、あまりにも熱心でない場合( "100%[^ \ nを]"、&都市を[* citiesCount ++]);' - > 'のscanf ( "%100 [^ \ n]"、cities [(* citiesCount)++]); ' – BLUEPIXY

+0

アンパサンドを削除しましたが、コンパイルが終了しましたが、最初の行の後ではクラッシュします。 – user3670471

+0

@xing 'citiesCount ++'は '(* citiesCount)++' – BLUEPIXY

答えて

0

あなたはこの1つは

void populate(int* citiesCount, char cities[][chars]) 
{ 
    for(int i = 0; (i < rows) && fgets(cities[i], chars, stdin) ; i++) 
    { 
     // remove there if not required. 
     printf("%d\n", (*citiesCount)++); 
     printf("%s\n", cities[i]); 

    } 
} 
関連する問題