【发布时间】:2014-10-16 11:22:52
【问题描述】:
我正在尝试编写一个程序来模拟 DFA。我需要做的是从用户那里获取一些输入并将其保存在两个独立的数组中(将其用作行和列),然后创建第三个数组(2d)作为第一个值的表两个数组。
例如:array2 = {a, b} array1 ={q1,q2,q3} 数组[array1][array2] = (下表)
a b
========
q1| v1 v2
q2| v3 v4
q3| v5 v6
问题:
1) 我无法将字符串 q1,q2,q3... 保存在数组中
2)第二个数组值以某种方式覆盖了第一个数组值,(可能是因为我使用的变量与其计数器相同?如果我更改第二个循环的计数器变量,则会出现分段错误
如果有人能指出我做错了什么,那就太好了。
编辑:由于coolguy和jayesh的回答,分割问题得到了解决。我还有一个问题,array1 不返回字符串,它只返回字符,如果我输入 q1 它只返回 q。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
// Function declaration
void clearNewLines(void);
int main(int argc, char *argv[]){
// Number of states and number of alphabets of DFA
int numStates;
int numAlphabets;
// Array for name of alphabets, and name of states
char nameOfAlphabets[numAlphabets];
char nameOfStates[numStates];
// Saving transition table
char *transitionTable[numStates][numAlphabets];
// Read numStates
printf("Enter the number of STATES:");
scanf("%d",&numStates);
// Flush STDIN
clearNewLines();
// Read the nameOfStates
int i;
for(i=0;i<numStates;i++){
printf("Name of STATES:");
fgets(&nameOfStates[i], 100,stdin);
}// End of for-loop to read nameOfStates
// Read numAlphabets
printf("Enter the number of ALPHABETS: ");
scanf("%d", &numAlphabets);
// Flush STDIN
clearNewLines();
// Read name of alphabets
for(i=0;i<numAlphabets;i++){
printf("Name of ALPHABETS:");
nameOfAlphabets[i] = getchar();
// Flush STDIN
clearNewLines();
}// End for-loop to read alphabets
// Get the transitionTable[states][alphabets]
int row;
for(row=0;row<numStates;row++){
int col;
for(col=0;col<numAlphabets;col++){
printf("Enter Transition From %c to %c: ",nameOfStates[row],nameOfAlphabets[col]);
printf("\n");
}
}
return 0;
}// End of main function
/*
*
* clearNewLines - clear any newline character present at the STDIN
*/
void clearNewLines(void)
{
int c;
do
{
c = getchar();
} while (c != '\n' && c != EOF);
}
【问题讨论】:
标签: c arrays scanf fgets getchar