我有以下文本文件
@1234
5,4
@tfxc
01AAX
11AA1
@tfxc
11AA1
11111
我想从文本文件中读取时忽略@及其背后的数据,而5,4是我在二维数组中存储的矩阵的维数。
这是我的代码:
#include <stdio.h>
FILE *inp;
int main(void) {
int i, j;
int y = 0;
int x = 0;
char comma;
char arr = 0;
inp = fopen("App.txt", "r");
fscanf(inp, "%d", &x);
fscanf(inp, "%c", &comma);
fscanf(inp, "%d", &y);
char array[y][x];
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
fscanf(inp, "%c", &arr);
if ((arr == '1') || (arr == 'X') || (arr == '0') || (arr == 'A')) {
array[i][j] = arr;
} else {
j--;
}
printf("%c", arr);
}
}
}
我怎么能这样做?
答案 0 :(得分:2)
使用<script>
/*========================================================================
other Part of the Problem
======================================================================*/
function insertIntoTable(){
var idArray = [<% for (int i = 0; i < list1.size(); i++){%>"<%= list1.get(i) %>"<%= i + 1 < list1.size() ? ",":"" %><% } %>];
var nameArray = [<% for (int i = 0; i < list2.size(); i++){%>"<%= list2.get(i) %>"<%= i + 1 < list2.size() ? ",":"" %><% } %>];
var len = idArray.length;
for (index = 0; index < len; index=index+1){
var vname = idArray[index];
var vid = nameArray[index];
document.getElementById(vid).value=vname;
}
}
</script>
读取行,检查是否应忽略该行,否则解析该行以初始化矩阵。
以下是一个例子:
fgets()
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int i, j;
int y = 0, x = 0;
FILE *inp = fopen("App.txt", "r");
if(!inp){
perror("fopen\n");
exit(EXIT_FAILURE);
}
while(2 != fscanf(inp, "%d,%d", &x, &y)){
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
if(ch == EOF){
fprintf(stderr, "There is no dimension specified.\n");
exit(EXIT_FAILURE);
}
}
char array[y][x];
char format[32];
sprintf(format, "%%%d[01AX]%%c", x);
for (i = 0; i < y; i++) {
int status;
char newline = 0, buff[x+1];
status = fscanf(inp, format, buff, &newline);
if(status == 0 || status == 2 && newline != '\n'){//status 1 is OK
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
--i;
continue;
}
if(status == EOF){
fprintf(stderr, "Necessary data is missing.\n");
exit(EXIT_FAILURE);
}
memcpy(array[i], buff, x);
}
fclose(inp);
//check print
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
putchar(array[i][j]);
}
putchar('\n');
}
return 0;
}