我是 c 初学者,所以我在让用户输入姓氏、逗号和名字时遇到问题。但是它将传递给函数调用
int get_name(FILE *fp)
在我的主要功能中。如果我必须使用参数参数,我就会遇到问题。
示例,main (int argc, char *argv[])) 或只是 main (void))
从我到目前为止的搜索来看,FILE*fp无法让用户从标准输入输入,它仅用于打开文件(?)但我需要让用户从键盘输入并传递给函数。我写了一些代码。但它们似乎不起作用,但我将在这里写下我确信我最需要进行一些更改的内容。
#define LINESIZE1024
int main(void){
FILE *fp;
char line[LINESIZE];
char first;
char last;
char comma;
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(fp = (sscanf(line,"%s %s %s",&last,&comma,&first)==3))
get_name(fp);
if(get_last_first(fp)== -1)
break;
printf("Please enter first name a comma and then last name");
}
但是我收到一个错误,说我无法将其从指针传递到整数。还有更多,但我不小心关闭了我的控制台,并且在我尝试修复时出现的所有错误都消失了。所以请给我一些想法。
辅助代码怎么样
while(1){
if(!fgets(line,LINESIZE,fp)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s %s %s",last,comma,first)==3)
get_last_first(fp);
return 0;
}
它也给了我错误。 fp,last,first,逗号在此函数中未初始化
好的,我想我现在已经解决了之前的问题。但是,如果名称给出正确,它不会打印回名称。这是我固定的主要代码。
int main(void){
FILE *fp = stdin;
char line[LINESIZE];
char first[16];
char last[16];
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s ,%s",last,first)==2)
if(get_name(fp)==2)
printf("Your name is: %s %s\n", first, last);
}
return 0;
}
这是我的函数。
int get_name(FILE *fp){
char line[LINESIZE];
char last[16], first[16];
int n;
/* returns -1 if the input is not in the correct format
or the name is not valid */
if(fgets(line, LINESIZE, fp) == NULL) {
return -1;
}
/* returns 0 on EOF */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == EOF) {
return 0;
}
/* prints the name if it's valid */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == 2) {
return 2;
}
return 1;
}
非常感谢你们花时间阅读和帮助我。请不要刻薄:)
最佳答案
看来你让它变得比需要的更复杂。不要在 main
中调用 fgets
和 scanf
。仅在函数 get_name
中执行此操作。
它可以是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 1024
int get_name(FILE *fp)
{
char line[LINESIZE];
char* t;
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
t = strstr(line, ",");
if (t)
{
*t = '\0';
++t;
printf("First: %s - Last: %s\n", line, t);
return 2;
}
printf("Illegal input\n");
return 0;
}
int main(int argc, char **argv)
{
get_name(stdin);
return 0;
}
如果您稍后决定要从文件中读取数据,则可以重复使用函数get_name
,而无需对其进行任何更改。您所需要的只是更改main
。喜欢:
int main(int argc, char **argv)
{
FILE* f = fopen("test.txt", "r");
if (f)
{
get_name(f);
fclose(f);
}
else
{
printf("Open file failed\n");
}
return 0;
}
关于c - 让用户输入名称但使用文件流 *fp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44495104/