![](/img/trans.png)
[英]In C, I wrote a program to call an exe using system(). The exe asks for user input. How can I make my program provide the input?
[英]I wrote a program to get user input and write it in a text file But it stuck after getting two inputs
我编写了一个程序来获取用户输入并将其写入文本文件但在获得两个输入后它卡住了。 它不停地重复。 如果我输入两个用户的详细信息,它会在该部分的 while(.feof(fp)) 中重复。 但连续输入相同的用户输入它可以正常工作。
#include <stdio.h>
int main(){
FILE *fp;
int i,flag = 0;
char loyaltyNumber[10],loyaltyFile[10];
char userInput[30];
char fileInput[30];
fp = fopen("loyalty.dat","w");
if ( fp == NULL)
{
printf("Cannot create file\n"); //checking file can be created or not
return -1;
}
fprintf(fp,"7728369210 Dinesh\n");
fprintf(fp,"7773457219 Subash\n");
fclose(fp);
fp = fopen("loyalty.dat","a+");
if ( fp == NULL)
{
printf("Cannot create file\n"); //checking file can be created or not
return -1;
}
for (i = 0; i < 5; i++){
printf("Enter loyalty number<space>Custormer name : ");
scanf("%s %s", &loyaltyNumber, &userInput);
while (!feof(fp)){
flag = 0;
if (strcmp(loyaltyFile,loyaltyNumber) == 0){
printf("Already exsisted\n");
flag = 1;
break;
}
fscanf(fp,"%s %s",&loyaltyFile, &fileInput);
}
if (flag == 0){
fprintf(fp,"%s %s",loyaltyNumber,userInput);
}
}
fclose(fp);
return 0;
}
不要在scanf()
和fscanf()
中将&
与%s
一起使用,而是替换fscanf(fp,"%s %s",&loyaltyFile, &fileInput);
使用fscanf(fp,"%s %s",loyaltyFile, fileInput);
和scanf("%s %s", &loyaltyNumber, &userInput);
with scanf("%s %s", loyaltyNumber, userInput);
. 另外, loyaltyNumber
包含一个包含 10 个字符的字符串,因此您应该将数组大小设置为 11 而不是 10,因为它没有足够的空间在数组末尾放置\0
并放置fseek(fp, 0, SEEK_SET);
在for (i = 0; i < 5; i++){
之后将文件指针更改为文件的开头,因为每次迭代都检查strcmp(loyaltyFile,loyaltyNumber) == 0
直到文件末尾。 最后但并非最不重要的一点是,您还应该在fprintf(fp,"%s %s",loyaltyNumber,userInput);
末尾添加一个\n
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.