在循环中收集字符串并打印出循环外的所有字符串

标签 c string pointers loops char

我是新手,有一些问题想请教大家。 例如:

#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/

相关文章:

c - 如何将 char* 字符串类型中的 "\n"从 ""更改为 0x104567910?

python - 为什么 Python 函数可以返回本地声明的数组而 C 不能?

c++ - Rust 中指针和引用的区别

c++ - 指向数组指针的指针

c++ - C和C++中的内存管理有什么区别

c - 发送 ICMP ping

c - 如何左移大于 64 位的值?警告 : shift count >= width of type [-Wshift-count-overflow]

c - 有没有一种方法可以快速确定从(稀疏)文件中读取的 block 是否全为零?

xml - 如果给出无效数据,AS3 XML 对象不会抛出异常?

algorithm - 反转 sprintf/format 的方法