c - 在 C 中向后循环名称

标签 c arrays string loops

我想从 n 次开始向后打印我的名字 (n = 1-100)。我似乎无法弄清楚。正如您从我的代码中看到的, strrev() 在循环时不起作用,因为它不断地一遍又一遍地反转。我还想以某种方式强制用户输入字母而不是数字作为名称,但这并不是必需的。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main () 
{
    int choice;
    char name[255];
    int loopCounter;
    int count;
    int number;

    do 
    {
        printf("1.Display Your Name\n");
        printf("2.Display Your Name (From 1-100)\n");
        printf("3.Display your Name Backwards\n");
        printf("4.Display Your Name Backwards (From 1-100)\n");
        printf("5.Quit\n");

        printf("Enter your name:\n");
        scanf("%s", name);

        printf("Enter your choice:   ");
        scanf("%i", &choice);

        switch(choice)
        {
            case 1: 
                printf("Your name is %s.\n", name);
                break;
            case 2:  
                printf("How many times to display your name? (1-100) ");
                scanf("%i", &count);

                if ( 100 < count) 
                {
                    printf("Please enter 1 through 100\n");
                }
                else 
                {
                    loopCounter = 0;
                    while (loopCounter < count ) 
                    {
                        loopCounter++;
                        printf("%d %s\n", loopCounter,name);
                    }
                }
                break;
            case 3:
                printf("Your name backwards is: %s\n\n", strrev(name));
                break;
            case 4:
                printf("How many times to display your name backwards? ");
                scanf("%i", &count);
                if ( 100 < count) 
                {
                    printf("Please enter 1 through 100\n");
                }
                else 
                {
                    loopCounter = 0;
                    while (loopCounter < count ) 
                    {
                        loopCounter++;
                        printf("%d %s\n", loopCounter, strrev(name));
                    }
                }
                break;
           case 5:
               printf("Goodbye!!!!\n");
               break;
           default:
               printf("Was not 1 through 5\n");
               break;
       }
   } while (choice!=5);
}   

最佳答案

您的问题是 strrev() 反转了字符串。

如果您想保留原始名称,则应该复制 name 并在循环之前使用 strrev() 将其反转一次。然后在循环中,只需调用反转的名称即可。

否则,只需执行以下操作:

loopCounter = 0;
strrev(name);
while (loopCounter < count ) {
    loopCounter++;
    printf("%d %s\n", loopCounter, name);
}

关于c - 在 C 中向后循环名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236712/

相关文章:

c - 读/写 tiff 图像 C

php - MySQL将数组保存在数据库中

javascript - 了解 .length 属性

C#如何比较两个字符串并指出哪些部分不同

c - HackerRank 上的对角线差异

c - 链表实现中的运行时错误

c - 编译器(通过链接时优化)如何处理快速返回的函数(提前退出路径)?

c++ - 为什么更改数组的第 0 个索引比第 0 个索引更改更多?

c - strcat 返回错误的字符

c++ - 程序在索引超出范围时终止