###前提・実現したいこと
C言語でファイルを読み込み、一部の要素を取り出してそれを演算しようとしています。
test.dat(読み込むファイル)
2018/01/15, Jan, 1, 10 2018/01/16, , 2, 10 2018/01/17, Jan, 1, 30 2018/01/18, Jan, 2, 15
実現したいこと(コメントアウトしている部分は表示しません)
./trial test.dat 1, 10 2, 10 1, 30 2, 15 1 40 //3列目が1の時、4列目の総和は10+30=40 2 25 //3列目が2の時、4列目の総和は10+15=25
###発生している問題・エラーメッセージ
発生しているエラーを読んでも理解できないため、アドバイスをいただけると幸いです。
trial.c: In function ‘main’: trial.c:28:7: error: a label can only be part of a statement and a declaration is not a statement int 1sum += num2; ^ trial.c:28:11: error: invalid suffix "sum" on integer constant int 1sum += num2; ^ trial.c:28:11: error: expected identifier or ‘(’ before numeric constant trial.c:31:7: error: a label can only be part of a statement and a declaration is not a statement int 2sum += num2; ^ trial.c:31:11: error: invalid suffix "sum" on integer constant int 2sum += num2; ^ trial1_15.c:31:11: error: expected identifier or ‘(’ before numeric constant trial.c:34:42: error: invalid suffix "sum" on integer constant printf("sum of line three is 1 =%d", 1sum); ^ trial.c:35:42: error: invalid suffix "sum" on integer constant printf("sum of line three is 2 =%d", 2sum); ^
###該当のソースコード
c
1 #include <stdio.h> 2 #include <stdlib.h> 3 4int main(int argc, char *argv[]){ 5 FILE* fp; // ファイルポインタ 6 7 char *fname = argv[1]; 8 fp = fopen(fname, "r"); // ファイルを開く 9 10 char line[256]; 11 int num1, num2; 12 char *p; 13 int c; 14//3列目と4列目の値を取得し、表示 15 while(fgets(line, sizeof(line), fp) != NULL) { 16 p = line; 17 c = 0; 18 while(p){ 19 if(*p == ',') c++; 20 p++; 21 if(c == 2) break; 22 } 23 sscanf(p, "%d,%d\n", &num1, &num2); 24 printf("%d,%d\n", num1, num2); 25 26//ここで総和を計算し、表示する 27 switch(num1){ 28 case 1: 29 int 1sum += num2; 30 break; 31 case 2: 32 int 2sum += num2; 33 break; 34 } 35 printf("sum of line three is 1 =%d", 1sum); 36 printf("sum of line three is 2 =%d", 2sum); 37 } 38 39 fclose(fp); 40 return 0; 41} 42 43}
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/01/16 12:02