[英]How to read in string input from the user and allocate it?
So I've been working on this code for a while now and I can't figure out why it's not working. 所以我已经在这段代码上工作了一段时间了,我不知道为什么它不起作用。 Basically I'm suppose to create a program using functions to read in string input from the user which is the filename for “data.txt”. 基本上,我想使用一个函数创建一个程序,以读取用户输入的字符串,即“ data.txt”的文件名。 I need a function to determine the number of rows that are in the file in order to allocate an array of character pointers. 我需要一个函数来确定文件中的行数,以便分配字符指针数组。 Then my program should print out the strings read from the file. 然后,我的程序应打印出从文件读取的字符串。 Finally the program should free the allocated memory. 最后,程序应释放分配的内存。
This is my non-working code. 这是我的无效代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_WIDTH 144
void getFileName(char* array1);
int getLineCount(FILE* data, int max);
char** createArryOfPtrs(int rows);
int main(void)
{
int max = 0;
int rows;
char array1[MAX_WIDTH];
FILE* data = fopen(array1, "r");
getFileName(array1);
getLineCount(data, max);
createArryOfPtrs(rows);
fclose(data);
return 0;
}
void getFileName(char* array1)
{
printf("Enter filename: ");
fscanf(stdin, "%144[^\t]", array1);
}
int getLineCount(FILE* data, int max)
{
int i = 4;
char *array1[MAX_WIDTH];
if(data != NULL)
{
while(fgets(*array1, MAX_WIDTH, data) != NULL)
{
i+=1;
}
}
return i;
}
char** createArryOfPtrs(int rows)
{
int r = 4, c = 9, i, j, count;
char *array1[r];
for(i =0; i < r; i++)
{
array1[i] = (char*)malloc(c * sizeof(char));
}
count = 0;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
array1[i][j] = ++count;
}
}
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf("%c", array1[i][j]);
}
}
return 0;
}
This is the text file. 这是文本文件。
larry snedden 123 mocking bird lane
sponge bob 321 bikini bottom beach
mary fleece 978 pasture road
hairy whodunit 456 get out of here now lane
I'm still new to C so I'm very confused. 我对C还是很陌生,所以非常困惑。 Appreciate any help I can get. 感谢我可以获得的任何帮助。
Order matters! 订单很重要! You get the name of the file to open after you call fopen
. 调用fopen
后,您将获得要打开的文件的名称。 That means the data in array1
will be uninitialized and indeterminate (and seem random). 这意味着array1
的数据将是未初始化和不确定的 (并且似乎是随机的)。
You need to read the name of the file first . 首先 ,您需要读取的文件的名称。
This issue should have been very clear if you did a little rubber duck debugging . 如果您做了一点橡皮鸭调试,这个问题应该已经很清楚了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.