Programming in C. I\'m working on a function that uses getline to get input from
ID: 3574019 • Letter: P
Question
Programming in C.
I'm working on a function that uses getline to get input from the user.
if the first word in a string of text is S, it will call a funtion that will save a 2Darray to a document.
the name of the file will be whatever the user types after the S.
So if the user were to type S myfile.txt, the function will save the file as myfile.txt.
This is the code that I have now, but I cannot get it to grabe the entire user input.
please correct pointers useage and passing a string into the filename
void copy_to_file(char** board, int num_rows, int num_cols, char* filename){
FILE *fp;
fp = fopen(filename.txt, "w");
int i =0;
int j = 0;
for (i = (num_rows - 1); i >= 0; --i) {
fprintf("%d ", i);
for (j = 0; j < num_cols; ++j) {
fprintf("%c ", board[i][j]);
}
fprintf(" ");
}
fprintf(" ");
for (i = 0; i < num_cols; ++i) {
fprintf("%d ", i);
}
fprintf(" ");
fclose(f);
}//end coppy to board
int main(int argc, char** argv)
{
char** board
do
{
printf("Enter your command: ");
fgets(command, 100, stdin);
if( command[1] == 's"){
copy_to_file(char** board, int num_rows, int num_cols, char* filename)
}
}while(!(get_valid_input(command)));
Explanation / Answer
Here is the workaround for your requirement.
#include <stdio.h>
void copy_to_file(char** board, int num_rows, int num_cols, char* filename){
printf("%s ", filename);
FILE *fp;
fp = fopen(filename, "w");
int i =0;
int j = 0;
for (i = (num_rows - 1); i >= 0; --i) {
fprintf(fp, "%d ", i);
for (j = 0; j < num_cols; ++j) {
fprintf(fp, "%c ", board[i][j]);
}
fprintf(fp, " ");
}
fprintf(fp, " ");
for (i = 0; i < num_cols; ++i) {
fprintf(fp, "%d ", i);
}
fprintf(fp, " ");
fclose(fp);
}//end coppy to board
int get_valid_input(char *cmd)
{
return 1;
}
int main(int argc, char** argv)
{
char** board, command[100];
int num_rows = 5, num_cols = 5;
do
{
printf("Enter your command: ");
fgets(command, 100, stdin);
if( command[0] == 'S'){
copy_to_file(board, num_rows, num_cols, command+2);
}
}while(!(get_valid_input(command)));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.