首先,这是代码:
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
FILE *stream;
int main()
{
int clients;
printf("Number of Clients: ");
scanf ("%d", &clients);
int age;
char name[100];
char gender[100];
char test[100];
for (int x = 0; x < clients; x++)
{
printf("Enter your name: ");
scanf("%s", &name[x]);
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your gender (M/F): ");
scanf("%s", &gender[x]);
stream = fopen ("input.txt", "w");
fprintf (stream, "Client #%d\n", x+1);
fputs ("Name: ", stream);
fputs (name, stream);
fprintf (stream, "\nAge: %d", age);
fputs ("\nGender: ", stream);
fputs (gender, stream);
fclose (stream);
}
system("input.txt");
stream = fopen ("input.txt", "w");
return 0;
}
当1个客户端正常时输出:
Client #1
Name: Jack
Age: 23
Gender: M
但是,当添加客户端数量时,一切都会出错:
Client #2
Name: JSam
Age: 10
Gender: MF
预期输出应为:
Client #1
Name: Jack
Age: 23
Gender: M
Client #2
Name: Sam
Age: 10
Gender: F
我尝试了但由于我没有编码经验而失败了:
如果有人能指出我做错了什么或者帮我修改代码,真的很感激。 我的主要目标是通过在for循环中使用fputs,fprints,fgets等来实现所谓的预期输出。
答案 0 :(得分:5)
好吧,你的第一个错误是你定义了一个100个字符的字符数组,然后你就像是一个双维数组一样增加它:
int age;
char name[100];
char gender[100];
char test[100];
让我们运行你的例子,这是你的数组的内存:
name = [ ][ ][ ][ ][ ][ ]
然后你在位置"Jack"
写下0
:
name = [J][a][c][k][\0]
然后你在位置"Sam"
写下1
:
name = [J][S][a][m][\0]
在这里你有你的错误!
所以基本上,你想要的是重用你的变量而不是无用地迭代它们(你可以感谢@Pandrei和@ M-Oehm纠正我的那部分):
int main()
{
int clients;
printf("Number of Clients: ");
scanf ("%d", &clients);
int age;
char name[100];
char gender;
char test[100];
stream = fopen ("input.txt", "w");
for (int x = 0; x < clients; x++) {
printf("Enter your name: ");
scanf("%s", &name); // here you rewrite your variable
printf("Enter your age: ");
scanf("%d", &age); // here you were already doing it
printf("Enter your gender (M/F): ");
scanf("%c ", &gender); // here you only need one character, you don't need a full string
fprintf (stream, "Client #%d\n", x+1);
fputs ("Name: ", stream);
fputs (name, stream);
fprintf (stream, "\nAge: %d", age);
fputs ("\nGender: ", stream);
fputs (gender, stream);
}
fclose (stream);
// I don't understand what you meant below, but executing a text file might not work, and if it works could be **really** dangerous, the below should be erased!
// system("input.txt");
// here you open again a stream without using it!
// stream = fopen ("input.txt", "w");
return 0;
}
请注意,如果使用长度超过100个字符的名称,则可能会遇到缓冲区溢出问题。这就是为什么你最好使用fgets()
代替scanf()
。
但你绝对应该首先打开Kernighan and Ritchie book并阅读有关内存管理,字符数组又名字符串的章节......
您还应该查看Stack Overflow上有关“为什么scanf很危险?”或FAQ entry
的答案