0

C program

I am trying to get user input strings

store them and then write them to a text file

I first prompt user for input the user enters 1 to input information.

user input are as follows

q1,q2,q3

q1

q3

q1,0,q2

y to save to file

type file name

program saves file.

However the inputs doesn't seem to be retained when trying to print or write later on in the program.

#include
#include
#include
int main() {
FILE * fpointer;
int createOrLoad;
char states[149];
char initialState[1];
char finalState[1];
char countinue = 'y';
char savePath[100];
char save;
printf("1 - Enter DFA 2 - Read DFA\n");
scanf("%d", &createOrLoad);
getchar();
  
if (createOrLoad == 1){
printf("Enter States (comma separated list):\n");
scanf("%s", &states);
getchar();
printf("%s\n", states);
  
printf("Enter initial state\n");
   scanf("%s", &initialState);
   getchar();
   printf("%s\n", initialState);
  
   printf("Enter final states\n");
scanf("%s", &finalState);
getchar();
printf("%s\n", finalState);
  
printf("%s\n%s\n%s\n", states, initialState, finalState);
  
char *transitions[25][7];
int transPosition = 0;
printf("Enter its transitions\n");
while(countinue == 'y') {
   scanf("%s", &transitions[transPosition]);
   getchar();
       transPosition++;
       printf("Another transition (y or n)?\n");
           scanf("%s", &countinue);
       }
       int i;
   for(i=0;i<1;i++) {
       printf("%s\n", transitions[i]);
       }
   printf("Would you like to save this DFA (y or n)?\n");
scanf("%s", &save);

printf("%s\n%s\n%s\n", states, initialState, finalState);
  
   if(save == 'y') {
printf("What file path name:\n");
scanf("%s", &savePath);
getchar();
fpointer = fopen(savePath, "w");
fprintf(fpointer, "%s\n", states);
fprintf(fpointer, "%s\n", initialState);
fprintf(fpointer, "%s\n", finalState);
fclose(fpointer);
  
   }
   }
   else{
  
   /*char fileName;
  
printf("file name to load\n");
scanf("%s", &fileName);
fpointer = fopen(fileName, "r");
char singleLine[100];
  
while(!feof(fpointer)){
fgets(singleLine, 100, fpointer);
puts(singleLine);
  
}*/
}
return 0;
  • 1
    How much is getting printed? That can help you to understand program's flow. – Swanand May 09 '21 at 04:38
  • In your commented-out code, it looks like you already found out [Why while ( !feof (file) ) is always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) Additionally, you cannot use ANY input function correctly unless you ***check the return*** to determine whether the input succeeded or failed. – David C. Rankin May 09 '21 at 06:03
  • Why do you declare, e.g. `char initialState[1];` (a one character array?) Why not simply `char initialState`? Both can store one-character worth of data. – David C. Rankin May 09 '21 at 06:13
  • _one-character worth of data_ is not enough for a _state_. – Armali May 09 '21 at 16:38

0 Answers0