我是新手,有一些问题想请教大家。 例如:
#include <stdio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
char name[51],selection;
do
{
printf("Enter name: ");
fflush(stdin);
fgets(name,51,stdin);
printf("Enter another name?(Y/N)");
scanf("%c",&selection);
selection=toupper(selection);
}while (selection=='Y');
//I want to printout the entered name here but dunno the coding
printf("END\n");
system("pause");
}
据我所知,循环执行何时会覆盖变量,那么我如何执行编码以打印出用户输入的所有名称? 我已经问过我的导师,他让我使用指针,这种情况下谁能指导我?
最佳答案
您基本上有两个选择,创建一个包含所有名称的列表,在最后遍历每个名称,或者在您读取它们时将所有名称连接成一个字符串,并在最后打印整个缓冲区。第一个大致是这样的:
char ch[2]="Y", names[100][52]; //store up to 100 50-char names (leaving space for \n and \0)
int x, nnames=0;
while(nnames<100 && *ch=='Y'){
fgets(names[nnames++], sizeof names[0], stdin); //since names is a 2d array, look
//only at the length of a row, (in this case, names[0])
fgets(ch, 2, stdin);
*ch = toupper(*ch);
}
for(x=0; x<nnames; x++)
//print names[x].
第二个大致是这样的:
char names[100*52], *np=names, *ep=names+sizeof names; //an array, the position, and the end
char ch[2]="Y";
while(np<ep && *ch=='Y'){
fgets(np, ep-np, stdin); //read a name, and a newline into the buffer
//note how I use the difference between the end and the position to tell
//fgets the most it can possibly read
np+=strlen(np); //advance the position to the end of what we read.
//same deal with the y/n stuff...
}
printf("%s", names);
注意最后没有循环,因为整个字符串都存储在名称中。
关于在循环中收集字符串并打印出循环外的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371931/